Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
/koaPublic
Uni Sayo edited this pageJan 28, 2019 ·14 revisions

Error handling is much easier in koa.You can finally use try/catch!

Catching downstream errors

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   *   ...  */});

Usingctx.throw

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');});

Usingctx.assert

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.
Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp