failing gracefully
Scala provides a util
package which provides a handy Try
type, with its companions Success
and Failure
.
This reminds me very much of standard promise handling in JavaScript browser apps.
Here’s a little code to try an http call (this one is destined to fail). When it fails, the “failure” will throw a nasty exception java.io.FileNotFoundException
with stack trace. We can catch that error and return it as an instance of Failure
, to be unwrapped later by some code which is ready for it.
From the terminal:
And the Failure
class has lots of useful methods to unwrap the data.
Not saying we should always swallow stack traces…usually a bad idea. But in some cases, it is helpful to know that an error may be coming and to handle it gracefully.