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?
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.
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. })
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With