I have CompletableFuture which can return result or exception. I want to perform run some common code in case of exception and normal result. Similar to try catch finally block
Current implementation
CompletableFuture<Integer> future= CompletableFuture.supplyAsync(this::findAccountNumber)
.thenApply(this::calculateBalance)
.thenApply(this::notifyBalance)
.exceptionally(ex -> {
//My Exception Handling logic
return 0;
});
Where i can put my finally logic ?
The closest equivalent to finally is whenComplete. Like handle, it accepts a function receiving either, a result value or a throwable, but it doesn’t provide a substitution result value, but rather, the new completion stage will not alter the result, just like finally.
So
static int decode(String s) {
try {
return Integer.parseInt(s);
}
finally {
System.out.println("finally action");
}
}
is equivalent to
static int decode1(String s) {
return CompletableFuture.completedFuture(s)
.thenApply(Integer::parseInt)
.whenComplete((myParsedInt, error) -> System.out.println("finally action"))
.join();
}
So when using with
for(String s: Arrays.asList("1234", "foo bar")) try {
System.out.println("decoded: "+decode(s));
} catch(Exception ex) {
System.out.println("decoding "+s+" failed with "+ex);
}
the first variant prints
finally action
decoded: 1234
finally action
decoding foo bar failed with java.lang.NumberFormatException: For input string: "foo bar"
and the latter prints
finally action
decoded: 1234
finally action
decoding foo bar failed with java.util.concurrent.CompletionException: java.lang.NumberFormatException: For input string: "foo bar"
Common to both is that an exception thrown within the finally action will supersede the original result, shadowing the exception, if the try block/ previous stage completed exceptionally.
handle() Method provide more flexible approach. it takes a function receiving either correct result or exception:
From java doc
handle(BiFunction<? super T,Throwable,? extends U> fn)
Returns a new CompletionStage that, when this stage completes either
normally or exceptionally, is executed with this stage's result and
exception as arguments to the supplied function.
CompletableFuture<Integer> thenApply = CompletableFuture.supplyAsync(this::findAccountNumber)
.thenApply(this::calculateBalance)
.thenApply(this::notifyBalance)
.handle((ok, ex) -> {
System.out.println("Code That we want to run in finally ");
if (ok != null) {
System.out.println("No Exception !!");
} else {
System.out.println("Got Exception " + ex.getMessage());
return -1;
}
return ok;
});
Related
I have a kotlinjs app. I handle a particular event (dropping of data onto a component) like this:
onEvent {
drop = { event ->
GlobalScope.async {
//...
dropTask(y, data)
}
}
}
// ...
// this function has to be a suspend function because model's is
private suspend fun dropTask(y: Int, taskId: TaskId) {
// ... prepare data
model.insertBefore(taskId!!, insertBefore?.id)
}
// ... Model's function is defined like this:
suspend fun insertBefore(taskToInsert: TaskId, taskBefore: TaskId?) {
val (src, _) = memory.find(taskToInsert)
// ... and finally, the find function is:
fun find(taskId: TaskId): Pair<Task?, Int> {
// ...
return if (task != null) {
// ...
} else {
throw Exception("Couldn't find task with id $taskId!!")
}
}
The issue is that the Exception gets thrown, but isn't reported anywhere.
I have tried:
a) Installing a CoroutineExceptionHandler into the GlobalScope.async (i.e.:
val handler = CoroutineExceptionHandler { _, e ->
console.log("Caught exception: $e")
}
GlobalScope.async(handler) {
...but this never gets called. This would be relatively clean if I could make it work. It would be even nicer if this was default behavior for kotlinjs, so that exceptions weren't accidentally unreported.
b) Calling await:
drop = { event ->
GlobalScope.launch {
GlobalScope.async() {
// ...
dropTask(y, data)
}.await()
}
}
This does result in the exception being logged to the console, but it's so ugly. It's not possible to call .await() outside of a suspend function or coroutine, so for this particular event handler I have to wrap the async call in a launch. I must be doing something wrong. Anybody have a better pattern that I should be using?
I have a service that calls a dependency via REST. Service and dependency are part of a microservice architecture, so I'd like to use resilience patterns. My goals are:
Have a circuit-breaker to protect the dependency when it's struggling
Limit the time the call can run. The service has an SLA and has to answer in a certain time. On timeout we use the fallback value.
Limit the number of concurrent calls to the dependency. Usually the rate of calls is low and the responses are fast, but we want to protect the dependency against bursts and queue requests inside the service.
Below is my current code. It works, but ideally I'd like to use the TimeLimiter and Bulkhead classes as they seem to be built to work together.
How can I write this better?
#Component
class FooService(#Autowired val circuitBreakerRegistry: CircuitBreakerRegistry)
{
...
// State machine to take load off the dependency when slow or unresponsive
private val circuitBreaker = circuitBreakerRegistry
.circuitBreaker("fooService")
// Limit parallel requests to dependency
private var semaphore = Semaphore(maxParallelRequests)
// The protected function
private suspend fun makeHttpCall(customerId: String): Boolean {
val client = webClientProvider.getCachedWebClient(baseUrl)
val response = client
.head()
.uri("/the/request/url")
.awaitExchange()
return when (val status = response.rawStatusCode()) {
200 -> true
204 -> false
else -> throw Exception(
"Foo service responded with invalid status code: $status"
)
}
}
// Main function
suspend fun isFoo(someId: String): Boolean {
try {
return circuitBreaker.executeSuspendFunction {
semaphore.withPermit {
try {
withTimeout(timeoutMs) {
makeHttpCall(someId)
}
} catch (e: TimeoutCancellationException) {
// This exception has to be converted because
// the circuit-breaker ignores CancellationException
throw Exception("Call to foo service timed out")
}
}
}
} catch (e: CallNotPermittedException) {
logger.error { "Call to foo blocked by circuit breaker" }
} catch (e: Exception) {
logger.error { "Exception while calling foo service: ${e.message}" }
}
// Fallback
return true
}
}
Ideally I'd like to write something like the docs describe for Flows:
// Main function
suspend fun isFoo(someId: String): Boolean {
return monoOf(makeHttpCall(someId))
.bulkhead(bulkhead)
.timeLimiter(timeLimiter)
.circuitBreaker(circuitBreaker)
}
You could also use Resilience4j's Bulkhead instead of your own Semaphore and Resilience4j's TimeLimiter.
You can stack you CircuitBreaker with bulkhead.executeSuspendFunction and timelimiter.executeSuspendFunction.
I keep wanting to do this:
do {
let result = try getAThing()
} catch {
//error
}
do {
let anotherResult = try getAnotherThing(result) //Error - result out of scope
} catch {
//error
}
But seem only to be able to do this:
do {
let result = try getAThing()
do {
let anotherResult = try getAnotherThing(result)
} catch {
//error
}
} catch {
//error
}
Is there a way to keep an immutable result in scope without having to nest do/catch blocks? Is there a way to guard against the error similar to how we use the guard statement as an inverse of if/else blocks?
In Swift 1.2, you can separate the declaration of the constant from the assignment of the constant. (See "Constants are now more powerful and consistent" in the Swift 1.2 Blog Entry.) So, combining that with the Swift 2 error handling, you can do:
let result: ThingType
do {
result = try getAThing()
} catch {
// error handling, e.g. return or throw
}
do {
let anotherResult = try getAnotherThing(result)
} catch {
// different error handling
}
Alternatively, sometimes we don't really need two different do-catch statements and a single catch will handle both potential thrown errors in one block:
do {
let result = try getAThing()
let anotherResult = try getAnotherThing(result)
} catch {
// common error handling here
}
It just depends on what type of handling you need.
How to test wether a function in Swift 2.0 throws or not? How to assert that the correct ErrorType is thrown?
EDIT: Updated the code for Swift 4.1 (still valid with Swift 5.2)
Here's the latest Swift version of Fyodor Volchyok's answer who used XCTAssertThrowsError:
enum MyError: Error {
case someExpectedError
case someUnexpectedError
}
func functionThatThrows() throws {
throw MyError.someExpectedError
}
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
XCTAssertEqual(error as! MyError, MyError.someExpectedError)
}
}
If your Error enum has associated values, you can either have your Error enum conform to Equatable, or use the if case statement:
enum MyError: Error, Equatable {
case someExpectedError
case someUnexpectedError
case associatedValueError(value: Int)
}
func functionThatThrows() throws {
throw MyError.associatedValueError(value: 10)
}
// Equatable pattern: simplest solution if you have a simple associated value that can be tested inside 1 XCTAssertEqual
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
XCTAssertEqual(error as! MyError, MyError.associatedValueError(value: 10))
}
}
// if case pattern: useful if you have one or more associated values more or less complex (struct, classes...)
func testFunctionThatThrows() {
XCTAssertThrowsError(try functionThatThrows()) { error in
guard case MyError.associatedValueError(let value) = error else {
return XCTFail()
}
XCTAssertEqual(value, 10)
// if you have several values or if they require more complex tests, you can do it here
}
}
At least of Xcode 7.3 (maybe earlier) you could use built-in XCTAssertThrowsError():
XCTAssertThrowsError(try methodThatThrows())
If nothing is thrown during test you'll see something like this:
If you want to check if thrown error is of some concrete type, you could use errorHandler parameter of XCTAssertThrowsError():
enum Error: ErrorType {
case SomeExpectedError
case SomeUnexpectedError
}
func functionThatThrows() throws {
throw Error.SomeExpectedError
}
XCTAssertThrowsError(try functionThatThrows(), "some message") { (error) in
XCTAssertEqual(error as? Error, Error.SomeExpectedError)
}
Given the following functions and declarations:
enum SomeError: ErrorType {
case FifthError
case FirstError
}
func throwingFunction(x: Int) throws {
switch x {
case 1:
throw SomeError.FirstError
case 5:
throw SomeError.FifthError
default:
return
}
}
This function will throw a FifthError if 5 is given to the function and FirstError if 1 is given.
To test, that a function successfully runs the unit test could look as follows:
func testNotError() {
guard let _ = try? throwingFunction(2) else {
XCTFail("Error thrown")
return
}
}
The let _ may also be replaced by any other name, so you can further test the output.
To assert that a function throws, no matter what ErrorType the unit test could look like this:
func testError() {
if let _ = try? throwingFunction(5) {
XCTFail("No error thrown")
return
}
}
If you want to test for a specific ErrorType it's done with a do-catch-statement. This is not the best way compared to other languages.
You have to make sure that you...
return in the catch for the correct ErrorType
XCTFail() and return for all other catch
XCTFail() if no catch is executed
Given this requirements a test case could look like this:
func testFifthError() {
do {
try throwingFunction(5)
} catch SomeError.FifthError {
return
} catch {
XCTFail("Wrong error thrown")
return
}
XCTFail("No error thrown")
}
Swift 4.1 Error throwing Test for associated values
enum ParseError: Error, Equatable {
case unexpectedArgument(String)
}
func testWithNoSchemaButWithOneArgument() {
XCTAssertThrowsError(try Args(withSchema: "", andArguments: ["-x"])) { error in
XCTAssertEqual(error as? ParseError, ParseError.unexpectedArgument("Argument(s) -x unexpected."))
}
}
You can use this function:
func XCTAssertThrowsError<T, E: Error & Equatable>(
_ expression: #autoclosure () throws -> T,
error: E,
in file: StaticString = #file,
line: UInt = #line
) {
var thrownError: Error?
XCTAssertThrowsError(
try expression(),
file: file,
line: line) {
thrownError = $0
}
XCTAssertTrue(
thrownError is E,
"Unexpected error type: \(type(of: thrownError))",
file: file,
line: line
)
XCTAssertEqual(
thrownError as? E,
error,
file: file,
line: line
)
}
Example:
XCTAssertThrowsError(try funcThatThrowsSpecificError(), error: SpecificErrorEnum.someError)
HI i am a little confused about how to transfer if_else error handling to do try catch successfully.
Here is my code.
let error : NSError?
if(managedObjectContext!.save()) {
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
if error != nil {
print(error?.localizedDescription)
}
}
else {
print("abort")
abort()
}
and now i converted to swift 2.0 like this
do {
try managedObjectContext!.save()
}
catch {
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
print((error as NSError).localizedDescription)
}
I am confused about where to print abort and do the abort() function
Any idea~? Thanks a lot
Rewriting your code to work the same as your original code
do {
try managedObjectContext!.save()
//this happens when save did pass
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
//this error variable has nothing to do with save in your original code
if error != nil {
print(error?.localizedDescription)
}
}
catch {
//this happens when save() doesn't pass
abort()
}
what you probably want to write is the following:
do {
try managedObjectContext!.save()
//this happens when save did pass
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
}
catch let saveError as NSError {
//this happens when save() doesn't pass
print(saveError.localizedDescription)
abort()
}
Everything within do {} is good, everything within catch {} is bad
do {
try managedObjectContext!.save()
NSNotificationCenter.defaultCenter().postNotificationName("updateUndoState", object: nil)
}
catch let error as NSError {
print(error.localizedDescription)
abort()
}
use either the error handling or the abort() statement