If at any point, I get an error, by trying to do something with an undefined, my entire express app crashes with a TypeError, instead of handling it nicely by redirecting to an HTTP 500 page.
Is there any way to handle these exceptions generally, or I will need to manually check in my router methods?
Have you tried this from the docs - Express Error handling?
Error-handling middleware are defined just like regular middleware, however must be defined with an arity of 4, that is the signature (err, req, res, next):
app.use(function(err, req, res, next) { console.error(err.stack); res.send(500, 'Something broke!'); });Though not mandatory error-handling middleware are typically defined very last...
Maybe try { ... } catch(e) {...} is what you are looking for?
Or just checks if value is not undefined. Simple if (value) { ... will do the job
As mentioned by phenomenal you can use express error handler middle-ware to handle error at centralized place.
app.use(function(err, req, res, next) {
console.error(err.stack);
res.send(500, 'Something broke!');
});
Than to pass error from your routes you can use next to pass error to this middle-ware like this
app.get('/login',function(req,res,next){
next("your error"); // The error middle-ware handle this error.
})