Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork3.2k
Error Handling
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 doestry { 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{awaitnext();}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 aboutctx.throwhere.
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 bodyctx.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 400ctx.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 bodythrownewError('Error Message');});
Read more information aboutctx.asserthere.
This is a shortcut function for usingctx.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);awaitnext();});
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.