Error handling
Error handling in Alette Signal is performed by handling fatal, recoverable and unknown errors either locally or globally.
Local error handling
To handle errors locally for mounted requests, extract the error using getState().error
, or by subscribing to the request state using when()
:
const deletePost = mutation(/* ... */)
const { getState, when, execute } = deletePost.mount();
when(({ isError, error }) => {
if (isError && error) {
console.log('Failed with an error:', { error })
}
})
execute()
// Or
// After request failure...
const { isError, error } = getState()
if (isError && error) {
console.log('Failed with an error:', { error })
}
To handle errors locally for one shot requests, wrap the request in try/catch
:
try {
await deletePost.execute()
} catch (error) {
if (error instanceof RequestFailedError) {
console.log('Failed with an error:', { error })
}
}
TIP
To understand what request state combination represents failure, refer to the request state combination documentation.
TIP
To understand how to retry errors, refer to the Alette Signal error retrying guide.
Global error handling
To handle errors globally in Alette Signal, set a global error handler using the setErrorHandler()
api instruction:
api.tell(
setErrorHandler((error, { context }) => {
// Your custom logic
}),
)
Global error handlers can also be async:
setErrorHandler(async (error, { context }) => {
// Your custom logic
})
WARNING
You can have only one global error handler active.
DANGER
Requests executed inside the global error handler will not complete if the system was shutdown after a fatal error was caught automatically.
api.tell(
setErrorHandler(async (error, {context}) => {
if (error instanceof FatalApiError) {
// Will never finish
await reportError.execute({ args: error.toString() })
}
})
)
const myRequest = query(
/* ... */
// Will fail with a fatal error and
// crash the system.
path('invalid path')
);
await myRequest.execute()
To match a specific error type, use instanceof
:
api.tell(
setErrorHandler((error) => {
if (error instanceof UnknownErrorCaught) {
// Your custom logic
}
}),
)
To send an error for global error handling, use the handleError()
api instruction:
api.tell(
setErrorHandler((error) => {
// Your custom logic
}),
)
api.tell(
handleError(new MyError())
)
DANGER
- Sending fatal errors manually to the global error handler will crash the system.
- Recoverable errors are not sent to the global error handler automatically.
WARNING
Manual error sending is used mostly for testing - avoid using handleError()
in production code.