【HAVENT原創】KOA2 異常處理

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);
    }
});

 

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
相關文章
相關標籤/搜索