KOA2 全局异常处理,首先在顶部引入下面的 错误捕捉中间件,然后在底部引用 NodeJS 未捕获异常拦截 即可。
注意:一般情况 错误捕捉中间件 就能完整基本的错误拦截,但是在引发未捕获异常时必须先用 NodeJS 未捕获异常拦截 之后才能捕获异常,否则会直接抛出异常,导致程序崩溃!
错误捕捉中间件:
/**
* 错误捕捉中间件
*/
app.use(async(ctx, next) => {
try {
ctx.error = (code, message) => {
console.log('threw error');
if (typeof code === 'string') {
message = code;
code = 500;
}
ctx.throw(code || 500, message || '服务器错误');
};
await next();
} catch (e) {
let status = e.status || 500;
let message = e.message || '服务器错误';
ctx.body = { status, message };
// 手动释放 error 事件
ctx.app.emit('error', e, ctx);
}
});
NodeJS 未捕获异常拦截:
process.on('uncaughtException', function (err) {
console.error('An uncaught error occurred!');
//console.error(err.stack);
console.log(new Date(), " uncaughtException:", err.message, err.status);
});
抛出异常语法:
// ctx 环境变量
// statusCode http错误码,错误码是有限制的,无效的错误码会被替换为500,错误码请看附录
// message 异常描述,可选
// param 异常携带的参数, 可选
ctx.throw(statusCode [, message], [param])
附录:
Status Code | Constructor Name |
---|---|
400 | BadRequest |
401 | Unauthorized |
402 | PaymentRequired |
403 | Forbidden |
404 | NotFound |
405 | MethodNotAllowed |
406 | NotAcceptable |
407 | ProxyAuthenticationRequired |
408 | RequestTimeout |
409 | Conflict |
410 | Gone |
411 | LengthRequired |
412 | PreconditionFailed |
413 | PayloadTooLarge |
414 | URITooLong |
415 | UnsupportedMediaType |
416 | RangeNotSatisfiable |
417 | ExpectationFailed |
418 | ImATeapot |
421 | MisdirectedRequest |
422 | UnprocessableEntity |
423 | Locked |
424 | FailedDependency |
425 | UnorderedCollection |
426 | UpgradeRequired |
428 | PreconditionRequired |
429 | TooManyRequests |
431 | RequestHeaderFieldsTooLarge |
451 | UnavailableForLegalReasons |
500 | InternalServerError |
501 | NotImplemented |
502 | BadGateway |
503 | ServiceUnavailable |
504 | GatewayTimeout |
505 | HTTPVersionNotSupported |
506 | VariantAlsoNegotiates |
507 | InsufficientStorage |
508 | LoopDetected |
509 | BandwidthLimitExceeded |
510 | NotExtended |
511 | NetworkAuthenticationRequired |