Handling Errors In Express Gracefully

Sai Umesh Dhanewar
Tech Buddy
Published in
2 min readJul 5, 2018

When I started working with Express, I didn’t know how easy it is to handle errors in it. Express framework gives you a nice way to handle your errors with some default functions as mentioned herehttps://expressjs.com/en/guide/error-handling.html

Even though Express gives you nice way to handle errors, that’s not enough to catch errors from your controllers.

with introduction of async-await in nodejs/javascript it has become very important to handle your errors gracefully, otherwise nodejs will through “Unhandled promise rejections are deprecated” error.

I see lot of examples on internet to solve this problem by wrapping your async await using try catch.

using try-catch is fine but, if you are writing large application, and writing
try catch for all routers result in lot of boiler plate code and also you can’t centralize all errors at one place, so let’s see how to do that.

In above example when you run “exceptionRoute” that would give you unhandled promise rejection error as discusssed. to avoid that problem we will wrap our function with try catch as seen in “ handleException”.

As we discussed above, try catch is fine but, if you are writing large application, that would result in lot of boiler plate code.

now if you run “ handleExceptionGraceFully”, you can see we are handling errors gracefully without try-catch which is awesome if you ask me.

The advantage of doing this is, we can centralize all our errors by taking advantage from express “next” function.

If you are interested in learning more about express you can refer to this article https://medium.com/tech-buddy/learn-expressjs-in-one-project-dd4c7c5e46c7.

Thanks for reading and Happy coding.

--

--