Yesterday, I talked about how to throw errors like a pro in Node.js, let’s take it further - handling errors in middleware. Most Node.js developers have one big error middleware that looks something like this: - Checks error type - Sends email to support - Logs the error - Sends the error to monitoring tools - Maybe even calls next() for some edge case And it’s all in one function. This works but it gets messy fast and It’s harder to test, scale, or read. A cleaner way is to break those actions into small services or functions. Then create an ErrorHandler class that runs them all. This way, your middleware stays clean, actions reusable and everything becomes easier to manage. See attached image for illustration. If your application needs another error tracking like slack notifications for example, it's easy to add the service. In the next post, I'll address graceful process exits and catching unhandled errors. stay tuned. #devs #nodejs
Helpful insight
Thanks for sharing