怎么在 koa 中,进行中间件的异常处理?
参考答案
标准写法
用 try/catch 包住 await next(),这样可以同时捕获下游中间件同步抛出和 await 的 Promise reject:
async function errorHandler(ctx, next) {
try {
await next();
} catch (err) {
ctx.status = err.status || err.statusCode || 500;
ctx.body = { code: ctx.status, message: err.message };
ctx.app.emit('error', err, ctx); // 交给全局监听做日志
}
}
分级处理
- 最外层(第一个
app.use)统一兜底:设置状态码、返回统一错误结构、记录日志,避免把堆栈泄露给客户端。 - 业务中间件内部:只处理自己能恢复的错误,其余
throw或ctx.throw(400, 'msg')交给上层。 - 全局监听:
app.on('error', (err, ctx) => logger.error(...)),防止未捕获异常导致进程退出。
补充
ctx.throw(status, message)会创建带status和expose的HttpError,外层catch后可直接用。- 未被
await的异步任务(如setTimeout里抛错)不会被捕获,需要process.on('unhandledRejection')/uncaughtException兜底,并配合优雅退出。 - 顺序很关键:错误处理中间件必须注册在所有业务中间件之前,否则捕获不到下游错误。