We currently have code like this
def somemethod() : Future[Resp] = {
val responseFuture = service.serveV2(req)
val nextFuture = responseFuture flatMap {
//do something on success including call to next async service
}
nextFuture
}
Of course, the map is being skipped on a timeout but I need to translate that timeout into a proper exception that I can pass up to our web framework to return the correct response code. How does one do this in scala?
Also of note is that I need to return that future. Maybe I should be creating a promise and wiring in responseFuture.onFailure into that promise or am I completely off base here? (I am wondering if there is an easier way or I could try to go down that path).
You might want to take a look at
recoverWithas it allows you to turn aThrowableinto anotherFuturethat can either be a failure or a success, depending on how you want to handle it. This is a bit more flexible than regularrecoverin that you don't always have to return a successful result in your transformation. So you could do something like this:If we get a successful future, the
flatMapwill take effect and therecoverWithwon't do anything as it's partial function won't match. If the future is failed with a non-TimeoutException when theflatMapwon't happen and therecoverWithwon't do anything either as the PF won't match. If it fails due to a TimeoutException then theflatMapwon't happen and therecoverWithwill kick in and turn it into a failed future wrapping a newSomeOtherException