DEV Community

Dibyojyoti Sanyal
Dibyojyoti Sanyal

Posted on

Error Handling with HTTP Error Response Generation in node.js Application

In one of my blog posts Separate routing from business logic in node.js | Central response generation in node.js we have seen how we can perform central HTTP response generation from the responses generated by the business logic module. In application different error conditions can occur. We would like to code for those error conditions using a try-catch, and throw constructs provided by the programming language. But that is not good when it comes to HTTP error responses. In cloud native application development we need to convert those errors to HTTP error responses. It would be necessary to handle the throws exceptions from code and convert them to HTTP error responses centrally.
We can create a errorHandler.js file where we write the code to convert the errors to HTTP responses.
The errorHandler will look like this

function errorHandler() {
  return (err, req, res, next) => {
    if (err instanceof TypeError) {
      return res.status(400).json( + ": " + err.message);
    if (err && err.statusCode) {
      return res.status(err.statusCode).json(err.body);
    return next(err);

module.exports = errorHandler;
Enter fullscreen mode Exit fullscreen mode

Then we need to import this errorHandler to the application server and apply it as app.use(errorHandler). In this way we don't have to convert error to HTTP response in every place, we just do it in one place. Of course, in all those files where error can occur we need to use try-catch-throw construct to throw errors. All those thrown errors will be caught by this block of code centrally.

For an complete example please refer to my blog post.

Discussion (0)