Centralizing and Handling Exceptions
Layered Architecture·4 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 Build Layered Services in Node.js module
Learn how to build well-structured, easily maintainable, and resilient microservices with the three-layer architecture.
You get immediate access to:
- 10 focused lessons across the three-layered architecture
- 1 real-world commented, step-by-step project
- Ongoing updates to this bundle
- Lifetime access to this bundle