I'm writing a series of REST APIs in Express and want to write a robust and consistent way of handling errors and presenting them to the user. So far I'm using middleware that looks like the following:
app.use(function(req, res, next){
res.render('404', { status: 404, error: 'not_found', error_description: 'the url '+req.url+' could not be found' });
});
app.use(function(err, req, res, next) {
switch (err.name) {
case 'CastError':
res.status(400);
return res.send({code:400, error: 'cast_error', error_description: err});
default:
console.log(err);
return res.send({code:500, error: 'internal_error', error_description: 'something went horribly wrong!'});
}
});
Now the problem comes in that errors can come from any part of the application. For example, Mongoose fires errors like 'CastError', there might be general system errors (unable to connect to the database) and there's also user validation errors.
Now some errors I want to present a message to the user (for example validation errors or telling them what was wrong with their API request), whereas others I want to hide from the user.
So looking at a validation error:
throw new Error('not a valid project id');
At the moment that'd just get caught as a generic 500 error and no useful message presented to the user. How can I differentiate the above error from a general system error so they can be handled differently? Is there an error type property I can make use of (perhaps err.name). If so, how do I use it?
Concept ideas (that obv don't work):
throw new Error('validation', 'not a valid project id');
Or
throw new Error('not a valid project id').name('validation');