Simplify Error Handling in ExpressJS

  • Sun May 07 2023
  • Jazim Abbas

If you would like to follow along with the code example that I am using, you can find the source code on the GitHub repository created by me.

Developers who work with asynchronous code in Express.js applications often face challenges when it comes to handling errors. By default, Express.js does not handle errors that occur in asynchronous code, leaving developers to manually catch and handle these errors. This can result in code that is difficult to read and maintain. Fortunately, the 'express-async-errors' package provides a solution to this problem. This package simplifies error handling in asynchronous code by automatically catching errors and passing them to Express.js error handling middleware, making it easier for developers to write clean and maintainable code.

Benefits & Limitations

Benefits

  • Simplifies error handling in asynchronous code by automatically catching errors and passing them to Express.js error handling middleware.
  • Improves code readability and maintainability by allowing developers to use try/catch blocks in asynchronous code.

Limitations

  • Only works with Express.js applications and does not provide a solution for error handling in other Node.js frameworks.
  • May not catch all types of errors that occur in asynchronous code, such as errors thrown in event handlers.

Overall, the 'express-async-errors' package can be a valuable tool for developers working with asynchronous code in Express.js applications, but it's important to be aware of its limitations and use it appropriately.

Best Practices

  • Import the "express-async-errors" package at the beginning of your code file, before defining any asynchronous route handlers or middleware. This ensures that any asynchronous code defined after the package is required or imported will be wrapped with the error handling functionality provided by the package.
    • By doing this, you can ensure that all asynchronous errors thrown in your application are caught by the package's error handling middleware and appropriately handled, rather than being left unhandled and potentially crashing your application.
  • Use try/catch blocks in asynchronous code to handle specific types of errors and provide appropriate responses to clients.
  • Avoid relying solely on 'express-async-errors' for error handling and always test error scenarios to ensure that your error handling code is working as expected.

Code Example

Custom Errors

class HttpError extends Error {
  statusCode;

  constructor({ message, statusCode }) {
    super(message);
    this.statusCode = statusCode || 500;
  }
}

class BadRequestError extends HttpError {
  statusCode = 400;
}

class NotFoundError extends HttpError {
  statusCode = 404;
}

class UnauthorizedError extends HttpError {
  statusCode = 401;
}

module.exports = { HttpError, BadRequestError, NotFoundError, UnauthorizedError };

First, I am creating some ES6 classes to help with creating custom errors. While you can use the built-in Error class, I have defined some additional classes in the code snippet to demonstrate various use cases. This is intended to show how you can catch exceptions and determine which type of error they belong to.

Exception Handling Middleware

This is a typical Express middleware function where we can define the logic for catching unhandled exceptions. In this case, we check if the error is an instance of the HttpError class. If it is, we update the status code and message accordingly. Finally, we return the response with the error message and status code, such as 400, 401, 500, etc.

const Errors = require("../libs/custom-errors");

module.exports = (err, req, res, next) => {
  let statusCode = 500;
  let message = "Server Error";

  if (err instanceof Errors.HttpError) {
    statusCode = err.statusCode;
    message = err.message;
  }

  res.status(statusCode).json({ message });
};

This is a simple example that you can customize according to your specific requirements. Feel free to add more complex logic as needed.

Routes

const router = require("express").Router();
const { BadRequestError, UnauthorizedError } = require("../libs/custom-errors");

router.get("/", (_, res) => res.json({ message: "Express Async Errors App" }));

router.post("/login", (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) {
    throw new BadRequestError({ message: "Email and Password are required fields" });
  }

  res.status(201).json({ message: "Successfully Login." });
});

router.get("/profile", (req, res) => {
  const token = req.header("Authorization");
  if (!token) throw new UnauthorizedError({ message: "You are not authorized." });

  res.json({ username: "Jazim Abbas", email: "jazim@gmail.com" });
});

module.exports = router;

As you can see in the code snippet above, I have not caught any exceptions. Instead, I am simply throwing an exception. The 'Unhandle Exception Middleware' will then catch the error and return a response with the appropriate error message and status code.

It's important to note that you can also catch and re-throw exceptions as needed. Regardless of how the exception is thrown, the middleware will catch all unhandled exceptions.

Setup File

const express = require("express");
require("express-async-errors");
const routes = require("./routes");
const unhandleExceptions = require("./middlewares/unhandle-exceptions");

const app = express();
app.use(express.json());
app.use("/", routes);
app.use(unhandleExceptions);

const PORT = process.env.PORT || 8000;
app.listen(PORT, () => console.log(`App is listening on the PORT ${PORT}...`));

Be sure to import the 'express-async-errors' package at the top of your file to catch any unhandled exceptions. Additionally, it's important to place the error-handling middleware at the end of the middleware chain, as this ensures it functions properly.

If you place the error-handling middleware at the top or in the middle, any exceptions thrown after the middleware won't be handled because of how Express.js works. It will instead pass the exception to the next middleware and so on, until it eventually run all the middlewares.

Conclusion

Overall, the 'express-async-errors' package provides a valuable solution for simplifying error handling in asynchronous code in Express.js applications. By automatically catching errors and passing them to Express.js error handling middleware, this package can help developers write clean and maintainable code.