U
U
user_of_toster2020-12-26 11:27:33
JavaScript
user_of_toster, 2020-12-26 11:27:33

Where to handle errors in nodejs?

I read Handle errors centrally. Not within middlewares

There is an encapsulated, central error handler:

module.exports.handler = new errorHandler();

function errorHandler() {
  this.handleError = async (err) => {
    await logger.logError(err);
    await sendMailToAdminIfCritical;
    await saveInOpsQueueIfCritical;
    await determineIfOperationalError;
  };
}


Further, if I want to use it in express \ koa, then I connect the error-handling middleware to the end, according to this scheme:
Some module throws an error -> API router catches the error -> it propagates the error to the middleware (eg Express, KOA) who is responsible for catching errors -> a centralized error handler is called -> the middleware is being told whether this error is an untrusted error (not operational) so it can restart the app gracefully.

// в конец после всех middleware
app.use((error, req, res, next) => {
    errorHandler.handleError(error)
}

However, it is written that
Note that it's a common, yet wrong, practice to handle errors within Express middleware – doing so will not cover errors that are thrown in non-web interfaces.

Question - where in this case to put the error handler, if not in the middleware?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WbICHA, 2020-12-26
@WblCHA

https://medium.com/devcbeirut/error-handling-js-ex...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question