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.name + ": " + 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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️