Nodejs快速将路由捕获错误转发给中间件

时间:2018-05-29 12:55:58

标签: node.js error-handling

我试图了解如何将nodejs express应用程序中的路由中发生的错误转发回错误处理程序,而不会抛出错误。

基本上我的中间件设置如下:

const allowedMethods = ['GET', 'POST'];

app.use(function (req, res, next) {
    if (!allowedMethods.includes(req.method))
        return res.sendStatus(405);
});

let paymentRoutes = require('./routes/payment');
app.use('/payment', paymentRoutes);

let notificationRoute = require('./routes/notifications');
app.use('/notifications', notificationRoute);

let customerRoutes = require('./routes/customer');
app.use('/customer', customerRoutes);

let subscriptionRoutes = require('./routes/subscription');
app.use('/subscription', subscriptionRoutes);


app.use(function (err, req, res, next) {
    console.log("error occured!");
    console.log(err);
    if (err) {
        console.log("Throwing an error!");
        next(err);
    } else {
        console.log("no error...")
    }
});

app.use(function logErrors (err, req, res, next) {
    winston.error(err);
    next(err);
});

app.use(function sendMailToAdmin(err, req, res, next) {
    //sendmailtoadmin
});

每当我在其中一条路线中抛出错误时,它就会正常工作。目前我在我的路线中处理这样的错误。

router.get('/:id/has-premium', (req, res) => {
    //throwing a test error
    throw new Error;
    const userId = req.params.id;
    customer.hasActivePremium(userId)
        .then(activePremium => {
            res.status(200).send(JSON.stringify({"success": true, "premium": activePremium}));
        })
        .catch(err => {
            res.status(err.httpCode).send(JSON.stringify({"success": false, "error": err.description}));
        })
});

我的问题是我如何“抓住”我的中间件错误处理程序,因为我抓住了承诺时遇到了错误?

1 个答案:

答案 0 :(得分:0)

您可以在路线签名中使用next,如

router.get('/:id/has-premium', (req, res,next) => {
//throwing a test error
throw new Error; // you can call next() here
const userId = req.params.id;
customer.hasActivePremium(userId)
    .then(activePremium => {
        res.status(200).send(JSON.stringify({"success": true, "premium": activePremium}));
    })
    .catch(err => {
        res.status(err.httpCode).send(JSON.stringify({"success": false, "error": err.description}));
    })

});

然后拨打next(err)而不是res.status(err.httpCode).send(JSON.stringify({"success": false, "error": err.description}));