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.9

Published

package helps you with http errors using express

Downloads

780

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

To install the package, use npm:

npm install express-http-error-handler

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 |


Usage

NotFoundError

userService.ts

In this example, we are trying to fetch a user by their ID. If the user does not exist in the database, a NotFoundError is thrown.

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

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

userController.ts

In the controller, we handle the request by catching the error and returning a proper HTTP response.

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

    async getUserById(req : Request, res : Response){
        try{
            const {id} = req.params;
            const user = await this.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

alt text


BadRequestError

userService.ts

This example checks if the email is provided when creating a new user. If it's missing, a BadRequestError is thrown.

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

    async createUser(data: any){
        if (!data.email) throw new BadRequestError('Email is required');
        return await this.prismaService.user.create({ data });
    }

userController.ts

In the controller, we handle the request by catching the error and returning a proper HTTP response.

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

    async createUserController(req: Request, res: Response) {
        try {
            const user = await this.userService.createUser(req.body);
            return res.status(201).json(user);
        } catch (error: any) {
            return error instanceof HttpError
                ? res.status(error.statusCode).json(error)
                : res.status(500).json(error);
        }
    }

Response

Description of the image

InternalServerError

paymentService.ts

In this example, we are processing a payment. If something goes wrong during the payment process, an InternalServerError is thrown.

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

    async processPaymentService(paymentData: any){
    try {
        // Process payment logic
        } catch (err) {
            throw new InternalServerError('Payment processing failed');
        }
    }

paymentController.ts

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

    async processPaymentController(req: Request, res: Response) {
        try {
            await this.paymentService.processPaymentService(req.body);
            return res.status(200).json({ message: 'Payment successful' });
        } catch (error: any) {
            return error instanceof HttpError
                ? res.status(error.statusCode).json(error)
                : res.status(500).json(error);
        }
    }

Response

alt text


UnauthorizedError

authService.ts

Here, we validate the user's authentication token. If the token is invalid, an UnauthorizedError is thrown.

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

    async getUserProfileService(token: string){
        const user = await this.authService.validateToken(token);
        if (!user) throw new UnauthorizedError('Invalid token');
        return user;
    }

authController

In the controller, we handle the request by catching the error and returning a proper HTTP response.

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

    async getUserProfileController(req: Request, res: Response) {
        try {
            const user = await this.authService.getUserProfileService(req.headers.authorization);
            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

alt text


ForbiddenError

adminService.ts

In this example, we are verifying if the user has the role of 'admin' before granting access to the admin panel. If the user is not an admin, a ForbiddenError is thrown.

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

    async accessAdminPanel(user: User){
        if (user.role !== 'admin') throw new ForbiddenError('Access denied: Admins only');
    }

adminController.ts

In the controller, we handle the request by catching the error and returning a proper HTTP response.

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

    async accessAdminPanelController(req: Request, res: Response) {
        try {
            await this.adminService.accessAdminPanelService(req.user);
            return res.status(200).json({ message: 'Welcome to the admin panel' });
        } catch (error: any) {
            return error instanceof HttpError
                ? res.status(error.statusCode).json(error)
                : res.status(500).json(error);
        }
    }   

Response

alt text