0

我不太明白如何捕捉我在路线深处抛出的错误,例如:

// put
router.put('/', async (ctx, next) => {
  let body = ctx.request.body || {}
  if (body._id === undefined) {
    // Throw the error.
    ctx.throw(400, '_id is required.')
  }
})

未提供 _id 时我会得到:

_id is required.

但我不会像在纯文本中那样扔掉它。我更喜欢在顶层捕获它然后格式化它,例如:

{
  status: 400.
  message: '_id is required.'
}

根据文档

app.use(async (ctx, next) => {
    try {
      await next()
    } catch (err) {
      ctx.status = err.status || 500

      console.log(ctx.status)
      ctx.body = err.message

      ctx.app.emit('error', err, ctx)
    }
  })

但即使在我的中间件中没有那个 try catch,我仍然得到_id is required.

有任何想法吗?

4

1 回答 1

1

使用所需的状态代码引发错误:

ctx.throw(400, '_id is required.');

并使用默认错误处理程序来格式化错误响应:

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.statusCode || err.status || 500;
    ctx.body = {
      status: ctx.status,
      message: err.message
    };
  }
});
于 2017-08-29T13:44:05.203 回答