Express 3 error middleware not being called

前端 未结 4 1907
温柔的废话
温柔的废话 2021-02-18 18:46

I am trying to setup error handling for my express app and running into the following problem.

I defined an error middleware and add it as the last middleware:



        
相关标签:
4条回答
  • 2021-02-18 19:06

    I had this problem as well, but I couldn't figure out why it wasn't working even though I set my error handler after the app.user(app.router). As it turns out, I already had an error handler that I wasn't aware of.

    Specifically, if you use the express cli to generate an app like I did, it will automatically add in this in:

    if ('development' == app.get('env')) {
      app.use(express.errorHandler());
    }
    

    Unfortunately for me, I added a bit more middleware to my app, which consequently obscured this statement and thus prevented my custom error handler from being called.

    Simply remove that and then it should work properly.

    On a side note, I should mention that the original solution still worked - even with the app.use(express.errorHandler()).

    app.all('*', function(err,req,res,next) {
        console.log('This is a global error handler at route level....');
        return next(err);
    });
    
    0 讨论(0)
  • 2021-02-18 19:06

    Updated answer for Express 4 users from the Express 4 docs. See example from docs below. Note that app.router is deprecated and no longer used. I also added a dummy route to make the ordering clear:

    "You define error-handling middleware last, after other app.use() and routes calls; For example:

    var bodyParser = require('body-parser');
    
    app.use(bodyParser());
    app.get('/', function(req, res) {
        res.send('hello world');
    })
    app.use(function(err, req, res, next) {
      // logic
    });
    

    "

    0 讨论(0)
  • 2021-02-18 19:14

    instead of making

    app.get('/datenschutz', function(req, res, next){
            return next(new Error('Just testing')); // handle everything here
        });
    

    you can install express-async-errors

    and just make

    app.get('/datenschutz', function(req, res){
           throw new Error('Just testing');
        });
    

    it works as expected

    0 讨论(0)
  • 2021-02-18 19:19

    EDIT 2 (sabtioagoIT) works. But just for those who missed it, emostar's solution also works. I understood to move the error handling 'use' call to the end, but there seems to be an easier option as emoster suggests, use app.router (before the error handling 'use' call).

    0 讨论(0)
提交回复
热议问题