Error handling
Aborting from handlers, and customizing error responses.
Aborting from handlers
Use abort() to short-circuit a handler and return an error response:
importfrom "@liveblocks/zenrouter";
zen.route
"GET /api/posts/<postId>",
asyncp=>
const post = awaitgetPostById
if!post) {
abort404
return
abort() throws internally and never returns. By default, it produces a JSON
response like { "error": "Not Found" } using the standard message for the
status code. You can customize the error shape with the router’s error handler
(see below).
Default error shape
By default, all error responses are JSON with at least an error key:
{ "error": "Not Found"For validation errors (422), a reason field is included with details:
{
"error": "Unprocessable Entity",
"reason": "Value at key 'title': expected string"
}Custom error handling
Use onError to customize the error response shape for all HTTP errors. For
example, when abort(404) is called, .onError() will get called with an
error object containing { status: 404, message: "Not Found" }:
zen.onErrorerror, { req, ctx=>
// error.status — the HTTP status code
// error.message — the error message
return json
new URL
});Use onUncaughtError to handle unexpected errors (bugs, unhandled exceptions):
zen.onUncaughtErrorerror, { req, ctx=>
error"Uncaught error:", error);
return json"Something went wrong"500
});Both handlers can only be registered once per router.
Shared error handler
If you use ZenRelay with multiple routers, you can share an ErrorHandler
instance across them:
importfrom "@liveblocks/zenrouter";
const errorHandler = new ErrorHandler
errorHandler.onErrorerror) =>
return json
});
const api = new ZenRouter
const admin = new ZenRouter
const app = new ZenRelayBuilt-in error responses
In addition to any abort() calls you make manually, Zen Router automatically
aborts under these conditions:
| Status | When |
|---|---|
| 400 Bad Request | Path params are malformed or fail validation |
| 403 Forbidden | authorize returns a falsy value |
| 404 Not Found | No route matches the URL |
| 405 Method Not Allowed | URL matches but HTTP method doesn’t |
| 422 Unprocessable Entity | Request body fails schema validation |
| 500 Internal Server Error | Uncaught error in a handler |
See also the Request lifecycle.