Error Handling
Throw NotFoundError, BadRequestError or ValidationError from any handler, catch errors in 4-argument error middleware, and control the JSON error response.
On this page6
Throw an error anywhere in a middleware or handler, synchronously or after an await, and AxilJS turns it into a JSON response. The HTTP error classes from @axiljs/common (re-exported by @axiljs/core) carry a status code and a machine-readable code, so the client gets the right status without any try/catch in your handler.
1import { Application, NotFoundError } from '@axiljs/core'
2
3const app = new Application()
4
5app.get('/users/:id', async (req, res) => {
6 const user = await users.find(req.params.id)
7 if (!user) throw new NotFoundError(`User ${req.params.id} not found`)
8 res.success(user)
9})HTTP/1.1 404 Not Found
{ "error": { "code": "NOT_FOUND", "message": "User 42 not found" } }Built-in error classes
| Class | Status | code | Constructor |
|---|---|---|---|
BadRequestError | 400 | BAD_REQUEST | (message?, details?) |
UnauthorizedError | 401 | UNAUTHORIZED | (message?) |
ForbiddenError | 403 | FORBIDDEN | (message?) |
NotFoundError | 404 | NOT_FOUND | (message?) |
ValidationError | 422 | VALIDATION_ERROR | (message?, details?) |
InternalError | 500 | INTERNAL_ERROR | (message?) |
All of them extend axilError, which has statusCode, code and an optional details.
Custom errors
Extend axilError (or call it directly) for domain-specific errors:
1import { axilError } from '@axiljs/core'
2
3export class PaymentRequiredError extends axilError {
4 constructor(message = 'Upgrade your plan to use this feature') {
5 super(message, 402, 'PAYMENT_REQUIRED')
6 this.name = 'PaymentRequiredError'
7 }
8}
9
10throw new axilError('Order already shipped', 409, 'ORDER_SHIPPED')The default error response
When no error middleware sends a response, AxilJS sends:
| Field | Value |
|---|---|
| status | err.statusCode for an axilError, otherwise 500 |
error.code | err.code for an axilError, otherwise INTERNAL_ERROR |
error.message | err.message, except a 500 in production, which becomes Internal server error |
error.stack | Included whenever NODE_ENV is not production |
details is not included in the default body. To return validation details to the client, add error middleware (below) or respond with res.validationError(...) directly.
Note
Set NODE_ENV=production in deployed environments. Outside production, stack traces are sent for every error, including 4xx.
Error middleware
A middleware with four parameters is registered as an error handler. Error handlers run in order when a handler throws or calls next(err).
1import { ValidationError, type ErrorMiddlewareFn } from '@axiljs/core'
2
3const onError: ErrorMiddlewareFn = (err, req, res, next) => {
4 logger.error('request failed', { path: req.path, error: err.message })
5
6 if (err instanceof ValidationError) {
7 res.status(422).json({
8 error: { code: err.code, message: err.message, details: err.details }
9 })
10 return
11 }
12
13 next(err) // fall through to the next handler or the default response
14}
15
16app.use(onError)- Calling
next(err)passes control to the next error handler; when none is left, the default response above is sent. - If an error handler itself throws, the new error goes to the next error handler.
- If headers are already sent (a stream or SSE in progress), the connection is ended instead of writing an error body.
Because AxilJS detects error handlers by function.length, write all four parameters even if you don't use next.
Errors from async code
Rejected promises in async handlers and middleware are caught the same way as synchronous throws; no wrapper is needed. Non-Error values (throw 'oops') are wrapped in an Error.
Related
Was this page helpful?