Hello,
I really like this post as I'm learning a better way of handling errors.
I have a question about when you add in the .catch(err) { next(err) }
Is this actually throwing out an error from server or I should still use like you did before throw new ErrorHandler(500, 'Internal server error');
Or that next(err)is doing it?
I just not get that and I would like to understand it.
I have an example of how I used:
async getAll(req, res, next) {
try {
const profiles = await db.Profile.find({});
if (!profiles)
throw new ErrorHandler(404, "No profiles are found!");
res.send({
profiles
});
next();
} catch (err) {
next(err);
}
},
Thanks for help :)
Since getAll is a middleware, it must call next() to tell the server to continue processing the next step after that, or else it will be blocked and never return any responses to the client. The error thrown in try block is then caught in catch block, through the name of err.
Therefore, calling next(err) means passing err to the next error-handling middleware while keeping the flow of your app running.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Hello,
I really like this post as I'm learning a better way of handling errors.
I have a question about when you add in the
.catch(err) { next(err) }
Is this actually throwing out an error from server or I should still use like you did before
throw new ErrorHandler(500, 'Internal server error');
Or that
next(err)
is doing it?I just not get that and I would like to understand it.
I have an example of how I used:
Since getAll is a middleware, it must call next() to tell the server to continue processing the next step after that, or else it will be blocked and never return any responses to the client. The error thrown in try block is then caught in catch block, through the name of err.
Therefore, calling next(err) means passing err to the next error-handling middleware while keeping the flow of your app running.