Node.js (Express) error handling middleware with router

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

Here\'s my application structure:

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

The ExpressJS app creates error handlers for development

2条回答
  •  野性不改
    2021-02-20 11:14

    You have to pass it to the next callback which is usually the third parameter in the route handler

    var router = express.Router();
    
    router.get('/', function (req, res, next) {
        someAsyncFunction(function(err, result) {
            if (err) {
                next(err); // Handle this error
            }
        }
    });
    
    module.exports = router;
    

    calling next(err) will allow the error to be caught in a middleware down the chain with the following signature:

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

    Reference: http://expressjs.com/en/guide/error-handling.html

提交回复
热议问题