express捕获全局异常的三种方法

场景

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');
原文地址:https://www.cnblogs.com/chenqionghe/p/11349521.html