Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log 500 status errors in console in express routes?

The typical errors I expect to see logged are not being logged in my express routes. for example:

router.get('/', function(req,res,next){
  console.log(undefinedVariable)
})

I expect to get an error:

ReferenceError: undefinedVarialbe is not defined;

however In the router.get I don't get any errors other than:

GET / 500 3.641 ms - 478

in my console which is making debugging hard. Is there any way to get these errors to show in the console?

like image 204
Robert M Avatar asked Jan 16 '17 16:01

Robert M


People also ask

How to catch Express error?

The simplest way of handling errors in Express applications is by putting the error handling logic in the individual route handler functions. We can either check for specific error conditions or use a try-catch block for intercepting the error condition before invoking the logic for handling the error.

How to catch error in middleware Express?

Catching Errors Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it. For example: app.get('/', (req, res) => { throw new Error('BROKEN') // Express will catch this on its own. })

What is next Express?

Understanding The next() Function The next() function is a function in the Express router that, when invoked, executes the next middleware in the middleware stack. If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function.


1 Answers

At the end of your routes, add this:

router.use(function (err, req, res, next) {
  if (err) {
    console.log('Error', err);
  } else {
    console.log('404')
  }
});

This will catch all routes that were not handled by a handler before it, and all routes that resulted in an error.

like image 185
Gregor Menih Avatar answered Nov 14 '22 21:11

Gregor Menih