KOA2 全局异常处理,首先在顶部引入下面的 错误捕捉中间件,而后在底部引用 NodeJS 未捕获异常拦截 便可。服务器
注意:通常状况 错误捕捉中间件 就能完整基本的错误拦截,可是在引起未捕获异常时必须先用 NodeJS 未捕获异常拦截 以后才能捕获异常,不然会直接抛出异常,致使程序崩溃!app
/** * 错误捕捉中间件 */ 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); } });
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 |