Node.js (Express) error handling middleware with router

后端 未结 2 1106
南旧
南旧 2021-02-20 10:15

Here\'s my application structure:

- app.js
- routes
---- index.js

The ExpressJS app creates error handlers for development

2条回答
  •  梦毁少年i
    2021-02-20 11:13

    You can also create a middleware function to handle error in all routes without copying code everywhere, using arrow functions if you like.

    1) Create a const function to handle errors.

    either:

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

    or

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

    2) In your router use it for every request:

    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) In your server main app handle 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: {}
        });
    });
    

    This way you can reuse the error handling function in any route. Also, if there are any unhandled errors in any of your functions, this will catch them as well.

    Try catch error handling taken from Here

提交回复
热议问题