failure

Error handling and exception management

Import

_ <- fat.failure

Methods

Name Signature Brief
trap (): Void Apply generic error handler
trapWith (handler: Method): Void Set a handler for errors in context
untrap (): Void Unset error handler in context

Usage Notes

When an error is created if an error handler is found, seeking from inner to outer execution context, the handler wrapping the failure is automatically invoked with that error as argument, and the calling context is exited with return value of the error handler.

it's not possible to set a handler for the global scope

trapWith

This method binds an error handler to the context of the calling site, e.g. when used inside a method it will only protect the logic executed inside the body of that method.

Example

Define an error handler that prints the error and exits:

console <- fat.console
system  <- fat.system
sdk     <- fat.sdk

simpleErrorHandler = (error) -> {
  console.log(error)
  sdk.printStack(10)
  system.exit(system.failureCode)
}

Finally, use trapWith method to assign the error handler:

failure <- fat.failure
failure.trapWith(simpleErrorHandler)

Trap it!

You can handle expected errors or pass through the unexpected:

failure <- fat.failure
_       <- fat.type.Error

MyError = Error

errorHandler = (error) -> {
  error == MyError => 0      # handle (expected)
  _                => error  # pass through (unexpected)
}

unsafeMethod = (n) -> {
  failure.trapWith(errorHandler)
  n < 10 ? MyError('arg is less than ten')
  n - 10
}

this only works if option -e / continue on error is not set

In this case the program will not crash if you call unsafeMethod(5), but if you comment out the trapWith line, you will see it crashing with MyError.

See also

results matching ""

    No results matching ""