9/4/2024
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.
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
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}
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});
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! 🚀
© 2024 - Made with ❤️ in Argentina 🇦🇷