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:
- 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
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.
- Once you have your middleware function defined it's time to pass it to express
To handle errors in your server application, you need to use the 'next' function from Express, as demonstrated below:
Example response:
This is just a way to handle possible server custom errors, this example were made with Typescript.
Top comments (0)