本文实例讲述了node.js 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');
希望本文所述对大家node.js程序设计有所帮助。
如对本文有疑问, 点击进行留言回复!!
使用npm命令提示: 'npm' 不是内部或外部命令,也不是可运行的程序的处理方法
Node Express用法详解【安装、使用、路由、中间件、模板引擎等】
Node Mongoose用法详解【Mongoose使用、Schema、对象、model文档等】
网友评论