Note that there are some explanatory texts on larger screens.

plurals
  1. POExpress 3 error middleware not being called
    text
    copied!<p>I am trying to setup error handling for my express app and running into the following problem.</p> <p>I defined an error middleware and add it as the last middleware:</p> <pre><code>// error handler app.use(function(err, req, res, next) { console.log('JUST TESTING. ERROR HANLDER HAS BEEN CALLED...'); next(err); }); </code></pre> <p>Now I would expect this middleware to be called whenever an error occurs:</p> <pre><code>app.get('/datenschutz', function(req, res, next){ return next(new Error('Just testing')); // handle everything here }); </code></pre> <p>However my middleware is never called! The browser does display the stack trace however. This seems that there is another middleware that is catching this error and processing it before I can do anything about it.</p> <p>The problem is that I have no clue where this middleware could be defined, as I have a very simple setup:</p> <pre><code>// setup ssl for local testing var app = express(); app. use(express.static(__dirname + '/public')). use(express.bodyParser()). use(express.cookieParser()); </code></pre> <p>Why is my error handling middleware not being called? Where is this 'default' error handling taking place?</p> <p>Thanks!</p> <p><strong>* EDIT *</strong> I see that the middleware is indeed working. However this is the case if I call it from another middleware function. However it is not being invoked if the error occurs inside a function defined as an express route (GET, POST, etc..). This is very strange. If I add my error middleware to the route callbacks it then works:</p> <pre><code>app.get('/testError', function(req, res, next){ return next(new Error('Just testing')); // handle everything here }, function(err,req,res,next) { console.log('This error handler is called!!'); return next(); }); </code></pre> <p><strong>* EDIT 2 - FOUND ACCEPTABLE WORKAROUND **</strong> I am surprised it has to be done this way. As I had read many entries/questions about error handling in express and never found this possibility mentioned. However it seems that if an error ocurrs inside a route callback regular error middleware handlers will not pick it up. You will need to define an error handler at route level.</p> <pre><code>app.all('*', function(err,req,res,next) { console.log('This is a global error handler at route level....'); return next(err); }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload