Javascript Node.js(Express)带有路由器的错误处理中间件

Javascript Node.js(Express)带有路由器的错误处理中间件,javascript,node.js,express,error-handling,Javascript,Node.js,Express,Error Handling,以下是我的应用程序结构: - app.js - routes ---- index.js ExpressJS应用程序为开发和生产环境创建错误处理程序。下面是来自app.js的代码片段: app.use('/', routes); // routing is handled by index.js in the routes folder //The following middleware are generated when you create the Express App // c

以下是我的应用程序结构:

- app.js
- routes
---- index.js
ExpressJS
应用程序为
开发
生产
环境创建错误处理程序。下面是来自
app.js
的代码片段:

app.use('/', routes); // routing is handled by index.js in the routes folder

//The following middleware are generated when you create the Express App

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error.ejs', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});
路由/index.js
的内部,我处理所有路由:

var router = express.Router();

router.get('/', function (req, res) {
    someAsyncFunction(function(err, result) {
        if (err) throw err; // Handle this error
    }
});

module.exports = router;

我希望将
err
传递给其中一个错误处理程序,而不是抛出。如何执行此操作?

您必须将其传递给下一个回调,该回调通常是路由处理程序中的第三个参数

var router = express.Router();

router.get('/', function (req, res, next) {
    someAsyncFunction(function(err, result) {
        if (err) {
            next(err); // Handle this error
        }
    }
});

module.exports = router;
调用
next(err)
将允许在具有以下签名的中间件中捕获错误:

app.use(function (err, req, res, next){
    // do something about the err
});

参考:

您还可以创建一个中间件函数来处理所有路由中的错误,而无需到处复制代码,如果您愿意,可以使用箭头函数

1)创建一个常量函数来处理错误

要么:

const handleErrorAsync = func => (req, res, next) => {
    func(req, res, next).catch((error) => next(error));
};

2)在您的路由器中,将其用于每个请求:

var router = express.Router();

router.get('/req1', handleErrorAsync(async (req, res, next) => {
   let result = await someAsyncFunction1();
   if(result){
       // res.send whatever
   }
}));
router.post('/req2', handleErrorAsync(async (req, res, next) => {
    let result = await someAsyncFunction2(req.body.param1);
    if(result){
        // res.send whatever
    }
}));
router.post('/req3', handleErrorAsync(async (req, res, next) => {
    let result = await someAsyncFunction3(req.body.param1, req.body.param2);
    if(result){
        // res.send whatever
    }
}));

module.exports = router;
3)在服务器主应用程序中处理错误:

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error.ejs', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});
这样,您可以在任何路由中重用错误处理功能。此外,如果在任何函数中存在任何未处理的错误,这也将捕获它们

尝试从中获取捕获错误处理

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error.ejs', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});