Common errors that can be thrown to simplify promise based api implementations
npm install rest-api-errorsHere's an example of an endpoint to delete a Thang.
``Javascript
// delete a thang
app.delete('/thangs/:id', function (req, resp) {
var username = req.user.username;
var id = req.params.id;
Thang.findOne({
_id: id
}).then(thang => {
if (!thang) {
// give em a 404 with custom error code and message
throw new NotFoundError('thang_not_found', "I can't find that thang :(");
} else if (thang.createdBy !== username) {
// give em a generic 403
throw new ForbiddenError();
}
// it's all good so actually delete the thang
return Thang.deleteOne({
_id: id
});
}).then(function () {
resp.status(204).end();
}).catch(function (err) {
if(err instanceof ApiError) {
// handle any ApiError with a simple elegant response
resp.status(err.status).send({
code: err.code,
message: err.message
});
} else {
// handle all other errors in some kinda way
handleError(resp, err);
}
});
};
``