-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Error Handling
Uni Sayo edited this page Jan 28, 2019
·
14 revisions
Error handling is much easier in koa. You can finally use try/catch!
In Express, you caught errors by adding an middleware with a (err, req, res, next)
signature as one of the last middleware.
In contrast, in koa you add a middleware that does try { await next() }
as one of the first middleware. It is also recommended that you emit an error on the application itself for centralized error reporting, retaining the default behaviour in Koa.
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
ctx.status = err.status || 500;
ctx.body = err.message;
ctx.app.emit('error', err, ctx);
}
});
app.on('error', (err, ctx) => {
/* centralized error handling:
* console.log error
* write error to log file
* save error and request information to database if ctx.request match condition
* ...
*/
});
Read more information about ctx.throw
here.
It is important to note that status codes 5xx will not expose the error message to the response body.
//This will set status and message.
app.use(async (ctx, next) => {
//will log the error as `InternalServerError: Error Message` and will return `Internal Server Error` as the response body
ctx.throw(500,'Error Message');
});
app.use(async (ctx, next) => {
//will NOT log the error and will return `Error Message` as the response body with status 400
ctx.throw(400,'Error Message');
});
app.use(async (ctx, next) => {
//This will log the error as `Error: Error Message` and will return `Internal Server Error` as the response body
throw new Error('Error Message');
});
Read more information about ctx.assert
here.
This is a shortcut function for using ctx.throw
when using with conditions.
app.use(async (ctx, next) => {
ctx.assert(ctx.request.accepts('xml'), 406);
// equivalent to:
// if (!ctx.request.accepts('xml')) ctx.throw(406);
await next();
});
This opens up a bunch of new possibilities:
- As you go down the stack, you can change error handlers very easily.
- You can handle errors in portions of your code much more easily.