Ezequiel Calonge

    Library for Handling HTTP Errors in Node.js

    Library for Handling HTTP Errors in Node.js

    nodejshttperrorshttp-errors

    9/4/2024

    2 min read

    Handling HTTP errors in Node.js can be a bit tricky, especially when you're dealing with different status codes and error messages. The @ezee/http-errors library is a handy tool that I created, that simplifies this process by providing a set of utility functions to create HTTP errors with ease.

    Why Use @ezee/http-errors

    • Simplicity: The library is designed to be simple and easy to use. You can create HTTP errors with just a single line of code.
    • Customization: You can customize the error messages and status codes according to your requirements.
    • Consistency: By using this library, you ensure that your error messages are consistent across your application.
    • Extra Metadata: You can attach additional metadata to the error objects for better debugging and logging.

    Installation

    You can install the @ezee/http-errors library using npm or yarn:

    1npm install @ezee/http-errors
    2
    3# using pnpm
    4pnpm install @ezee/http-errors
    5
    6# using yarn
    7yarn add @ezee/http-errors

    Usage

    Here's how you can use the library to create HTTP errors in your Node.js application:

    1import httpErrors from "@ezee/http-errors";
    2
    3// Create a 404 Not Found error
    4new httpErrors.NotFound({
    5  message: "Resource not found",
    6  code: "RESOURCE_NOT_FOUND",
    7  meta: {
    8    resource: "user",
    9    id: 123,
    10  },
    11});

    That will build an error object with the following structure:

    1{
    2  "name": "NotFound",
    3  "message": "Resource not found",
    4  "status": 404,
    5  "code": "RESOURCE_NOT_FOUND",
    6  "meta": {
    7    "resource": "user",
    8    "id": 123
    9  }
    10}

    Example usage with Express

    1import express from "express";
    2import httpErrors from "@ezee/http-errors";
    3
    4const app = express();
    5
    6app.get("/user/:id", (req, res, next) => {
    7  const { id } = req.params;
    8
    9  if (id !== "123") {
    10    return next(
    11      new httpErrors.Notfound({
    12        message: "User not found",
    13        code: "USER_NOT_FOUND",
    14        meta: {
    15          userId: id,
    16        },
    17      }),
    18    );
    19  }
    20
    21  res.json({ id, name: "John Doe" });
    22});

    Conclusion

    This library is a useful tool for handling HTTP errors in Node.js applications. It simplifies the process of creating error objects and provides a consistent way to manage errors across your application. Give it a try in your next project and see how it can help you manage HTTP errors more effectively. If you have any questions or feedback, feel free to reach out to me on GitHub.

    Happy coding! 🚀

    Resources

    © 2024 - Made with ❤️ in Argentina 🇦🇷