Centralize & Handle Errors

Layered Architecture·2 min read·Jan 1, 2025

Exception handling is the process of dealing with unwanted or unexpected events (errors) that might disrupt the normal execution flow of a computer program.

The error flow

In the current state of the application, any runtime errors thrown either by the Service layer or the Data Access layer are intercepted by the Router layer, and then converted into a standard HTTP 500 Internal Server Error response, as illustrated by the following schemas.

In this first case, when an error is thrown by a service, it is directly caught by the calling controller.

In the second case, when an error is thrown by a repository, it is let through by the calling service — as it doesn't have a try...catch structure—to then be handled by the controller.

Although this approach technically works, the error response sent by the controller doesn't provide enough context for the client to know what went wrong with the request.

We could solve this by parsing the error directly within the catch block of the controller and adapting its response accordingly, but it would unfortunately give the controller more responsibilities than it should have.

Instead, a better solution would be for the controller to catch and rethrow these errors to a dedicated component in charge of the error handling logic, as illustrated by the following schema.

Creating a custom error-handling middleware

In Express, an error-handling middleware function is just like any other middleware, except that it takes four arguments instead of three, and must be declared at the very bottom of the call stack, after all the other components such as middlewares, routes, and routers.

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.