我不太明白如何捕捉我在路线深处抛出的错误,例如:
// 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.
有任何想法吗?