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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2024 CODEPRJ.COM