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-customize-errors

v1.0.14

Published

A light weight node express package that serves as a centralized error management system. This Package helps you serialize all errors in your express app before sending them back to the client, comes with built-in support for typescript

Downloads

56

Readme

express-customize-errors

A light weight node express package that serves as a centralized error management system. This Package helps you serialize all errors in your express app before sending them back to the client, comes with built-in support for typescript.

Installation

npm install express-customize-errors 

Basic Usage

Here is a simple example using typescript, to help you get the gist.

import express, { Request, Response, NextFunction } from 'express';
import { NotFoundError, ErrorHandler } from 'express-customize-errors';


const port = process.env.PORT || 3000;

const app = express();

app.all("*", ( req:Request,res:Response, next:NextFunction )=>{
    return next(new NotFoundError('Route Not Found')); // Expected output: { "errors": [{ "message": "Route not found" }] }
});

app.use(ErrorHandler);

app.listen(port, () =>{
    console.log(`LISTENING ON PORT ${port}`);
});

You can also create your own custom errors of by levelaging the custom error class as demonstrated in the example below:

Step 1

Inside your project create an errors folder and then create a file with a name of your choice where you are going to define your custom error signature. preferably use the actual name of the error.

Eg : /errors/database-connection-error.ts

Step 2

Import the CustomError class

import  CustomError from 'express-customize-errors';

Define error signature as follows:

export class DatabaseConnectionError extends CustomError {
    statusCode = 500;
    constructor(public message: string ) {
      super(message);
      Object.setPrototypeOf(this, DatabaseConnectionError.prototype);
    }
    serializeErrors() {
      return [{ message: this.message }];
    }
};

Once done now you can import this newly created error and use it across your entire application Let's use it inside app.ts file

import express, { Request, Response, NextFunction } from 'express';
// import in Errorhandler middleware & NotFoundError
import { NotFoundError, ErrorHandler } from 'express-customize-errors';
import  { DatabaseConnectionError } from './errors/database-connection-error';
import mongoose from 'mongoose';


const port = process.env.PORT || 3000;

const app = express();

app.all("*", ( req:Request,res:Response, next:NextFunction )=>{
    // pass a new extended custom error into the express nextFunction
    return next(new NotFoundError('Route Not Found'));   // Expected Output: { "errors": [{ "message": "Route not found" }] }

});
const connectDatabase = async () => {
  try{
      await mongoose.connect(process.env.MONGO_URI as string);
      console.log('CONNECTED TO DATABASE');
  }catch(err){
    return next({ err }); // Expected Output: { errors:[ { message: 'Internal Server Error' }] }
    throw new DatabaseConnectionError('Could not connect to DB'); // Expected Output: { errors:[ {message: 'Could not connect to DB'}] }
  }
};

// consume Error handler
app.use(ErrorHandler);

app.listen(port, () =>{
    console.log(`LISTENING ON PORT ${port}`);
});

connectDatabase();

Asyncronous Codes

If you wish to use custom errors inside an async fuction be sure to install and import express-async-errors package

npm install express-async-errors

Then simply import it in your server file eg: app.ts


import 'express-async-errors';

Usage with express-validator

npm install express-validator express-customize-errors

Create an errors folder in your root directory and inside this errors folder create a file and paste in the code below

 
import { CustomError, ExpressValidationError} from 'express-customize-errors';

export class RequestValidationError extends CustomError {
    statusCode= 400;
    constructor(private errors:ExpressValidationError[]){
        super('invalid request params');
        Object.setPrototypeOf(this, RequestValidationError.prototype);
    };
    serializeErrors(){
        console.log('this is  errors', this.errors);
        return this.errors.map(err => {
            return{ message: err.msg, field: err.path };
        })
    };
}

Now apply your RequestValidationError in application routes and services


import express, { Request, Response, NextFunction } from 'express';
import { body, validationResult } from 'express-validator';
import { RequestValidationError } from '../errors/requestValidationError';
import { convertToExpressValidationError } from 'express-customize-errors';
const router = express.Router({ mergeParams: true });

router.post('/api/auth/signup', [
    body('email')
        .isEmail()
        .withMessage('Invalid Email'),
    body('password')
        .trim()
        .isLength({ min: 4, max: 15 })
        .withMessage('Password must contain at least 4-15 chars')
], (req: Request, res: Response, next: NextFunction) => {
    console.log('req.body..', req.body);

    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        const expressErrors = convertToExpressValidationError(errors.array());
        return next(new RequestValidationError(expressErrors));
        // Expected output: 
        // {
        //   "errors": [
        //     {
        //       "message": "Invalid Email",
        //       "field": "email"
        //     },
        //     {
        //       "message": "Password must contain atleast 4-15 chars",
        //       "field": "password"
        //     }
        //   ]
        // }
    }
    console.log('creating a user...');
    return;
});

export { router as authRoutes };

CustomError constructor

Parameters and their respective types and requirements

| Name | Required | Type |
|---------------------------|-------------------------------|-------------------------------------------------------------------| | message | true | String | | field | false | String | | serializeErrors | true | function serializeErrors(): { message: string; field?: string }[];| | | | |

Built in Custom Errors Usage

| Name | StatusCode | Customizable Message | |---------------------------|-------------------------------|------------------------------------------------------------------| | BadRequestError | 400 | Eg: "Bad Request Error" | | NotFoundError | 404 | Eg: "Not Found" | | NotAuthorizedError | 401 | Eg: "Not Authorized " | | RequestValidationError | 403 | Eg: "Request Validation Failed" | |