DEV Community

Cover image for Error handling in Express Server - NodeJS
Marlon Yepes Ceballos
Marlon Yepes Ceballos

Posted on

Error handling in Express Server - NodeJS

When you want to develop a backend app using Node.js and Express as frameworks for server building, you must have a way to handle the errors that could occur during a service execution.
One way to prevent unhandled errors or non-execution responses is by using the middleware functions that Express allows us to use. Here is an example of how to catch and return a server response:

  • As a good practice normalize ur server response structures:

Common Http Server Response Interface

Error Http Server Response Interface

  • Once u have created interfaces for define ur server response object u have to create classes thath extends from Error native class for representing possible server errors

Common Http Error Exception Class

ResourceNotFound Exception Class

All errors in Node.js extend from the Error class. This allows you to create a custom error class, extend from it, and use reserved keys like 'throw' for throwing your custom errors. Now, you have to create the middleware function to use.

Http Error Middleware

  • Once you have your middleware function defined it's time to pass it to express

Middleware use setting

To handle errors in your server application, you need to use the 'next' function from Express, as demonstrated below:

Http Error Middleware use

Example response:

Image description

This is just a way to handle possible server custom errors, this example were made with Typescript.

Top comments (0)