Skip to content

handler map

Raphael Pigulla edited this page Apr 22, 2022 · 1 revision

MAP

Synopsis

Map an exception to a different one.

Description

This is arguably the most important handler. It transforms an exception to a different one, usually wrapping the original exception in the process. The new exception is thrown by default (thus sidestepping any remaining handlers), but this can be configured with the continue flag as detailled below.

A common use case it to configure this as the last handler in a chain to ensure that all errors that are not handled explicitly are handled.

Options

The following options are supported.

  • callback: (error, ...parameters) => Error | Promise<Error> (mandatory)
    The error thrown by the function will be replaced by the error returned by the callback. Note that the callback must return the new error, not throw it. The callback is invoked with the same context as the wrapped function (unless you use an arrow function).
  • scope: Class<Error> (optional)
    Limit the handler to exceptions of the given class (or any subclass thereof).
  • predicate: (error, ...parameters) => boolean | Promise<boolean> (optional)
    Dynamically skip invocation of the handler depending on the error thrown or any of the wrapped method's parameters. The predicate is invoked with the same context as the wrapped function (unless you use an arrow function).
  • onCallbackError: CallbackErrorAction (optional, defaults to THROW_WRAPPED)
    This option controls how errors thrown by the callback are handled.
    • THROW_WRAPPED: The error is wrapped in an MapError. This is the default.
    • THROW: The error is thrown as-is.
    • THROW_TRIGGER: The error is ignored and the triggering error is thrown instead.
  • continue: boolean (optional, defaults to false)
    By default, a mapped error is thrown immediately and no other handler is called. If you want to continue the chain of handlers (now with the mapped error), you can set this parameter to true.

Example

class Foo {
    @HandleError({
        // Note that no 'scope' is defined here
        action: HandlerAction.MAP,
        callback: error => new FooError({ cause: error }),
    })
    public async doSomething(): Promise<void> {
        // whatever happens here will never throw anything other than a FooError
    }
}