Nodejs——异常捕获

34 阅读1分钟

1.接口中异常 通过try-catch 捕获

2.express 中间件异常 通过 app.use 中间件捕获

app.use(function (err, req, res, next) {
    res.json(cFun.responseStatus(-1,JSON.stringify(err.stack)));
});

3.express 路由错误异常处理。 构建404 中间件

app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

4.回调函数中异常 例如在接口中启动定时器,在定时器中抛出异常

制造错误
var assert = require('assert');
    setTimeout(function () {
        assert(false); //这里主动触发异常
        res.send("hello");
    }, 1000);

捕获处理错误
function uncaughtExceptionHandler(err) {
    

process.exit(1);
}
process.on('uncaughtException', uncaughtExceptionHandler);