Nodejs - 如何捕捉抛出的错误并格式化它?
Nodejs - how to catch thrown error and format it?
我不太明白如何捕捉我在路线深处抛出的错误,例如:
// 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.'
}
根据 doc:
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.
有什么想法吗?
抛出所需状态代码的错误:
ctx.throw(400, '_id is required.');
并使用default error handler格式化错误响应:
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
};
}
});
我不太明白如何捕捉我在路线深处抛出的错误,例如:
// 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.'
}
根据 doc:
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.
有什么想法吗?
抛出所需状态代码的错误:
ctx.throw(400, '_id is required.');
并使用default error handler格式化错误响应:
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
};
}
});