「HAVENT原创」KOA2 异常处理
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 CodeConstructor Name400BadRequest401Unauthorized402PaymentRequired403Forbidden404NotFound405MethodNotAllowed406NotAcceptable407ProxyAuthenticationRequired408RequestTimeout409Conflict410Gone411LengthRequired412PreconditionFailed413PayloadTooLarge414URITooLong415UnsupportedMediaType416RangeNotSatisfiable417ExpectationFailed418ImATeapot421MisdirectedRequest422UnprocessableEntity423Locked424FailedDependency425UnorderedCollection426UpgradeRequired428PreconditionRequired429TooManyRequests431RequestHeaderFieldsTooLarge451UnavailableForLegalReasons500InternalServerError501NotImplemented502BadGateway503ServiceUnavailable504GatewayTimeout505HTTPVersionNotSupported506VariantAlsoNegotiates507InsufficientStorage508LoopDetected509BandwidthLimitExceeded510NotExtended511NetworkAuthenticationRequired