6. Koa Error Handling

1. Koa own error handling

  koa in to throw an exception by ctx.throw (state code), you can also bring their own want an error message 

// Here we restrict the importation of id can not be negative, otherwise it will throw an error 
usersRouter.get ( '/: id', (ctx) => {
   IF (ctx.params.id * 1 <0 ) { 
    ctx. The throw ( 404, 'the user is too small, not found' ) 
  } 
  ctx.body = DB [ctx.params.id *. 1 ] 
})

  

 

           FIG own error processing result 1 koa

  We can see from the figure, the returned status code 404, the error processing information is also displayed. But this is not what we want, in the prescribed Restful API, we try to return information using json format

  So we can write a middleware on the front of the order of execution, error-handling code to be executed later

//错误处理中间件
app.use(async (ctx, next) => {
  try {
    await next()
  } catch (error) {
    ctx.status = error.status || error.statusCode
    ctx.body = {
      message: error.message
    }
  }
})

 

 

   You can see the error message out on the show to Json format

 

2. Use the middleware koa-json-error to deal with error messages

 1. AnSo koa-json-error

  npm i koa-json-error --save

 2. Use 

const error = require('koa-json-error')
app.use(error())

 

 

               FIG 2 Error processing information koa-json-errorr

    As can be seen, the results koa-json-error is returned json format, and information is very full. But there is a stack field very long, at the production stage we do not need returned. So, we need to

  Hide it in a production environment

Guess you like

Origin www.cnblogs.com/zhanghaoblog/p/11707422.html