Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is ExecutionContext#reportFailure(Throwable) called?

Tags:

scala

This is a rather general question, but hopefully a reasonable one. When is ExecutionContext#reportFailure(Throwable) called?

It doesn't seem to be called in the Scala standard library. I suppose I perhaps should call it in some circumstances? What are these?

like image 329
Paul Draper Avatar asked May 31 '16 15:05

Paul Draper


2 Answers

This method reports exceptions that cannot be reported otherwise.

It is called when an exception happens during the execution of a callback that has no other way of reporting failure. In particular, calls to Future.onComplete (e.g. via Future.foreach) return Unit and may be executed on any thread, so they have no way of reporting failure back to their callers. When an exception is thrown within onComplete, it is sent to this method.

like image 81
Hosam Aly Avatar answered Sep 29 '22 21:09

Hosam Aly


It is called a couple of times deep within the implementation for Promise in the standard library. See the source.

try onComplete(value) catch { case NonFatal(e) => executor reportFailure e }

An ExecutionContext can implement reportFailure to execute arbitrary code when a future/promise fails. The only thing in the standard library that implements this method is ExecutionContextImpl, which is not in the public API, but found here. This class accepts a reporter: Throwable => Unit function. The default ExecutionContext.Implicits.global uses ExecutionContext.defaultReporter, which simply prints the stack trace to System.err.

If you wanted to customize the behavior, you could need to define your own ExecutionContext. It's difficult to imagine a scenario where you'd want to produce some other side-effect other than logging the stack trace, or some other kind of logging.

like image 24
Michael Zajac Avatar answered Sep 29 '22 20:09

Michael Zajac