This Simple Node.js Error Handling Trick Will Save You 100s of Lines of Code

Kyle Gawley
Kyle Gawley
Gravity Founder
This Simple Node.js Error Handling Trick Will Save You 100s of Lines of Code

Are you fed up writing try…catch in your Node.js application?Do this simple trick instead.

If you've been using the awesome async/await in the latest versions of Javascript you may also be familiar with the pain of repeatedly writing this throughout your application:

try {
  await somefunction()
catch(err) {
  // handle error

It's important that calls to an asynchronous function are wrapped in a try...catch so you can gracefully handle any errors without a full application crash.

The problem? It's messy, annoying and adds 100s of lines of unnecessary code throughout your application with error handling scattered all over the place.

The Solution

The best practice is to handle errors once with a few lines of code and eliminate try....catch completely. The following example uses Express but you can achieve this with any other type of router.

At the top of your API file(s), define this simple higher-order function (HOF).

const use = fn => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

Then wrap each call to your controller calls in this function:'/api/account', use(accountController.create));

This HOF will call your controller method and catch any errors before passing them along to the Express error handler (covered next).

The reason we place this at the API level is that this should be the highest level of your call stack. All controller and method functions will be executed from here once a request reaches your API, so we can catch any errors down the stack using this simple HOF.

Finally, in your server.js file, add these lines of code:

app.use(function(err, req, res, next){

  res.status(500).send({ message: err.sqlMessage || err });


This will catch any errors forwarded by the HOF, log them to the console and send an HTTP 500 status with the error that was caught.

That's it! Super simple to implement without re-factoring your code-base and will save you 100s of lines of code repeatedly typing try....catch in every function.

Download The Free SaaS Boilerplate

Build a full-stack web application using React, Tailwind, Node.js and Express.