Using Node.js + Express (4) + Mongoose (using promises, not callbacks), I cannot figure out how to remove my error handling.
I have (fairly simplified):
app.get('/xxx/:id', function(request, response) {
Xxx.findById(request.params.id).exec()
.then(function(xxx) {
if (xxx == null) throw Error('Xxx '+request.params.id+' not found');
response.send('Found xxx '+request.params.id);
})
.then(null, function(error) {
switch (error.name) {
case 'Error':
response.status(404).send(error.message);
break;
case 'CastError':
response.status(404).send('Invalid id '+request.params.id);
break;
default:
response.status(500).send(error.message);
break;
}
});
});
Here, in the switch under the "Failed Failure" section, Erroris the error that I selected for a potentially valid identifier that was not found CastError- this is Cast to ObjectId, which Mongoose shot down for an invalid id, and a 500 error could be caused, for example, an error throw Error()like throw Err()(to raise ReferenceError: Err is not defined).
But, like this, each of my routes has this big big awkward switch for handling various errors.
? - ?
( , throw error; " ", ).