一种方式是使用 koa-onerror 错误处理中间件,一种方式是使用 try...catch...
使用 koa-onerror
配置:
const koa = require('koa');
const onerror = require('koa-onerror');
const app = new koa();
// 404 Not Found
app.use(async (ctx, next) => {
await next()
if (ctx.status === 404) {
ctx.throw(404)
}
})
// error handler
onerror(app, {
accepts() {
return 'json';
},
json(err, ctx) {
ctx.body = {
code: ctx.status || 500,
msg: err.message
}
}
})
使用 ctx.throw([status], [msg], [properties]) 抛出异常,如:ctx.throw(401, 'id is required')
使用 try...catch...
// error handler
app.use(async (ctx, next) => {
try {
await next()
} catch (err) {
ctx.status = err.statusCode || err.status || 500
ctx.body = {
code: ctx.status,
msg: err.message
}
ctx.app.emit('error', err, ctx)
}
})
可以在控制台监听 error 事件,打印报错信息
// error logger
app.on('error', err => {
console.log('server error', err)
})