npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-http-error-handler

v1.0.13

Published

A lightweight package that simplifies handling and throwing HTTP errors in Express applications.

Downloads

12

Readme

express-http-error-handler

express-http-error-handler is a package for handling HTTP errors in Express applications in a simple and efficient way. It provides specific error classes for the most common HTTP status codes.

Installation and configuration

To install the package, use npm:

npm install express-http-error-handler

Now we have to enable these options in our tsconfig.json para poder utilizar decoradores en typescript.

"experimentalDecorators": true,
"emitDecoratorMetadata": true,  

Error List

Here are the available error classes in the package:

| Error Class | HTTP Status Code | Description | | --------------------- | ---------------- | -------------------------------------- | | NotFoundError | 404 | Represents a 404 Not Found error | | BadRequestError | 400 | Represents a 400 Bad Request error | | InternalServerError | 500 | Represents a 500 Internal Server Error | | UnauthorizedError | 401 | Represents a 401 Unauthorized error | | ForbiddenError | 403 | Represents a 403 Forbidden error |


Decorators List

These are some of the decorators providing for the moment

| Decorator | Description | | ---------------------| ---------------------------------------------------------------------------| | ResMethod | handles and validates the errors thrown and returns them to the customer |


Using Package with Typescript

suppose we have a service class called UserService

we created our basic methods

UserService.ts

import { NotFoundError} from 'express-http-error-handler';

export class UserService{

    constructor(){}

    async getUserById(id : string){
        const user = await this.user.findById(id);
        if(!user) throw new NotFoundError(`user not found with id ${id}`);
        return user;
    }
}

now in our controllers

we can use the decorator provided by express-http-error-handler, which helps us to handle and validate the thrown errors

it is not necessary using a try catch block, since this decorator does the error handling and validation for you, you just return your correct operation.

UserController.ts

import { Request, Response } from 'express';
import { ResMethod } from 'express-http-error-handler';

export class UserController{

    constructor(){}

    @ResMethod()
    async getUserById(req : Request, res : Response){
        const {id} = req.params;
        const user = await userService.getUserById(id);
        return res.status(200).json(user);
    }
}

Response

In this case, we throw a NotFoundError (status code 400) from our service, using our @ResMethod decorator, we handle this error and any other error that is not thrown using this package will also be handled by returning a status code 500.

The response client receives looks like this:

alt text


Example using javascript

As we know in pure JavaScript, decorators are not natively supported, so we can handle and trap our errors by simply validating the type of error in the try catch block of our controller.

UserController.js

import { Request, Response } from 'express';
import { HttpError } from 'express-http-error-handler';

export class UserController{

    constructor(){}

    async getUserById(req : Request, res : Response){
       try{
        const {id} = req.params;
        const user = await userService.getUserById(id);
        return res.status(200).json(user);
       }catch(error : any){
        return error instanceof HttpError
        ? res.status(error.statusCode).json(error)
        : res.status(500).json(error);
       }
    }
}

Response

the answer ends up being the same, the difference is that now we must validate the instance the error to know if it is of type HttpError

alt text

In this way we can use and thorw errors in express, either from services, middlewares or other validations.