場景
express的路由里拋出異常后,全局中間件沒辦法捕獲,需要在所有的路由函數里寫try catch,這坑爹的邏輯讓人每次都要多寫n行代碼
官方錯誤捕獲中件間代碼如下
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
測試證明客戶端已經卡死,沒有返回結果
解決方法一
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
});
雖然可以捕獲,在命令行有輸出,但是沒辦法給客戶端返回錯誤了
解決方法二
const Layer = require('express/lib/router/layer');
Object.defineProperty(Layer.prototype, 'handle', {
enumerable: true,
get() {
return this.__handle;
},
set(fn) {
if (fn.length === 4) {
this.__handle = fn;
} else {
this.__handle = (req, res, next) =>
Promise.resolve()
.then(() => fn(req, res, next))
.catch(next);
}
},
});
解決方法三
安裝express-async-errors,沒錯,已經有人受不了express不能捕獲Promise異常搞了個破解包
地址https://github.com/davidbanham/express-async-errors
npm install express-async-errors --save
使用
var express = require('express');
require('express-async-errors');