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

unified-errors-handler

v3.2.4

Published

Unified Errors Handler is A Powerful Error Handling Library for Node.js that unify error structure across application. it can unify database errors.

Downloads

30

Readme

Unified Errors Handler

Unified Errors Handler is A Powerful Error Handling Library for Node.js that unify error structure across application. it can unify database errors.

Latest Stable Version GitHub License NPM Downloads NPM Downloads

Content

  1. Installation
  2. Usage
    1. ExpressJS Middleware
    2. Custom ExpressJS Middleware
    3. NestJS Exception Filter
    4. Options
  3. Errors Structure
  4. General Exceptions
  5. SQL Database Exceptions
  6. No SQL Database Exceptions
  7. Custom Exceptions
  8. Logging
  9. Supported Database and ORMs
  10. Tests
  11. Support and Suggestions

Installation

$ npm i unified-errors-handler

Usage

  • ExpressJS Middleware

const express = require('express');
const { expressExceptionHandler } = require('unified-errors-handler');
const app = express();
/**
  response in case of error will be
  {
    errors: [
      {
        code: 'USER_NOT_FOUND',
        message: 'user not found',
      },
    ],
  }
  with status code 404
*/
app.post('/test', function (req, res) {
    const isFound = // ...
    if (isFound) {
      // return response
    } else {
      throw new NotFoundException([
        {
          code: 'USER_NOT_FOUND',
          message: 'user not found',
        },
      ]);
    }
});

app.use(expressExceptionHandler());
  • Custom ExpressJS Middleware

const express = require('express');
const { exceptionMapper } = require('unified-errors-handler');

const app = express();
/**
  response in case of error will be
  {
    errors: [
      {
        code: 'USER_NOT_FOUND',
        message: 'user not found',
      },
    ],
  }
  with status code 404
*/
app.post('/test', function (req, res) {
    const isFound = // ...
    if (isFound) {
      // return response
    } else {
      throw new NotFoundException([
        {
          code: 'USER_NOT_FOUND',
          message: 'user not found',
        },
      ]);
    }
});

app.use((err: Error, req: any, res: any, next: any) => {
    const mappedError = exceptionMapper(err);
   
    res.status(mappedError.statusCode).send({
      errors: mappedError.serializeErrors(),
    });
  });
  • NestJS Exception Filter

const { exceptionMapper } = require('unified-errors-handler');

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();

    const error = exceptionMapper(exception);
    const statusCode = error.statusCode;
    response.status(statusCode).json({
      errors: error.serializeErrors(),
    });
  }
}
  • Options

You can add options to (enable/disable) parsing for database errors (depends on your ORM) this is disabled by default, See supported ORMs

const options = {
    mapDBExceptions: true,            // deprecated
    parseSequelizeExceptions: true,
    parseMongooseExceptions: true,
    parseTypeORMExceptions: true,
    parseObjectionJSExceptions: true,
    parseKnexJSExceptions: false,
}

expressExceptionHandler(options)
// or 
const mappedError = exceptionMapper(err, options);

Unified Structure

{
   errors: [{
      fields: ['name', 'password'],   // optional
      code: 'YOUR_CODE',
      message: 'your message'
      details: {    // optional - more details about error
        key: value 
      }
   }]
}

Exceptions

  1. BadRequestException

  • Status code - 400
throw new BadRequestException({
  fields: ['password'],        // optional
  code: 'INVALID_PASSWORD',    // optional
  message: 'invalid password'
  details: {                  // optional
   // ... more details
  }
});
  1. UnauthorizedException

  • Status code - 401
throw new UnauthorizedException({
  code: 'UNAUTHORIZED',
  message: 'You are not authorized'
});
  1. ForbiddenException

  • Status code - 403
throw new ForbiddenException({
  code: 'FORBIDDEN',
  message: 'You have no access'
});
  1. NotFoundException

  • Status code - 404
throw new NotFoundException([
  {
     code: 'USER_NOT_FOUND',
     message: 'user not found',
  },
]);
  1. ServerException

  • Status code - 500
throw new ServerException();

SQL Database Exceptions

  1. UniqueViolationException

  • Status code - 400
// output
[
  {
    fields: ['name'],
    code: 'DATA_ALREADY_EXIST',
    message: 'name already exist',
  },
]
  1. ForeignKeyViolationException

  • Status code - 400
// output
// foreign key is not exist as primary key in another table
// trying insert value with invalid foreign key
[
  code: 'INVALID_DATA',
  message: 'Invalid data',
  details: {
    reason: 'violates foreign key constraint',
    constraint: 'pet_user_id_foreign',
  },
]
// foreign key has reference in another table 
[
  code: 'DATA_HAS_REFERENCE',
  message: 'Data has reference',
  details: {
    reason: 'violates foreign key constraint',
    constraint: 'pet_user_id_foreign',
  },
]
  1. NotNullViolationException

  • Status code - 400
// output
[
  {
    fields: ['age'],
    code: 'INVALID_DATA',
    message: 'age is invalid',
    details: { reason: 'age must not be NULL' },
  },
]
  1. CheckViolationException

  • Status code - 400
  • Example - Invalid enum value
// output
[{
  code: 'INVALID_VALUES',
  message: 'Invalid Values',
  details: {
    constraint: 'user_gender_check',
  },
}]
  1. OutOfRangeViolationException

  • Status code - 400
  • Example - numeric value out of range
// output
[{
  {
    code: 'OUT_OF_RANGE',
    message: 'Out of range',
  },
}]

No SQL Database Exceptions

  1. MongoDBUniqueViolationException

  • Status code - 400
// output
[
  {
    fields: ['name'],
    values: ['Ahmed'],
    code: 'DATA_ALREADY_EXIST',
    message: 'name already exist',
  },
]
  1. MongooseValidationException

  • Status code - 400
// output
[
  // field is required
  {
    fields: ['age'],
    message: 'Path `age` is required.',
    code: 'MONGODB_VALIDATION_ERROR',
    details: { 
      reason: 'age is required', 
      violate: 'required_validation'
    },
  },
  // field's value violate enum values
  {
    fields: ['gender'],
    message: '`MALEE` is not a valid enum value for path `gender`.',
    code: 'MONGODB_VALIDATION_ERROR',
    details: { 
      reason: "gender's value must be one of MALE, FEMALE", 
      violate: 'enum_validation'
    },
  },
  // field's value violate max value
  {
    fields: ['age'],
    message: 'Path `age` (300) is more than maximum allowed value (50).',
    code: 'MONGODB_VALIDATION_ERROR',
    details: { 
      reason: `age's value exceed maximum allowed value (50)`, 
      violate: 'max_validation'
    },
  },
  // field's value violate min value
  {
    fields: ['age'],
    message: 'Path `age` (3) is less than minimum allowed value (20).',
    code: 'MONGODB_VALIDATION_ERROR',
    details: { 
      reason: `age's value less than minimum allowed value (20)`, 
      violate: 'min_validation'
    },
  },
  // field's value violate type of field
  {
    fields: ['age'],
    message: 'age is invalid',
    code: 'MONGODB_CASTING_ERROR',
  },
]

Custom Exceptions

You can create your own exceptions by extend BaseException

export class MyCustomException extends BaseException {
  statusCode = 400;

  constructor(private message: string) {
    super(message);
    Object.setPrototypeOf(this, MyCustomException.prototype);
  }

  serializeErrors() {
    return [{
      message,
      code: 'CUSTOM_CODE'
    }];
  }
}

Logging

  1. ConsoleLogger

const options = {
  loggerOptions: {
    console: {
      format: ':time :message', // optional - default message only
      colored: true,    // optional - default no color
    },
  },
}

expressExceptionHandler(options)
// or 
const mappedError = exceptionMapper(err, options);
  1. CustomLogger

implement ILogger interface

import { ILogger } from 'unified-errors-handler';

class CustomLogger implements ILogger {
  log(error: any): void {
    console.log(error.message);
  }
}

// in options pass this object
const options = {
  loggerOptions: {
    custom: new CustomLogger(),
  },
}

expressExceptionHandler(options)
// or 
const mappedError = exceptionMapper(err, options);

Supported Database and ORMs

  1. MYSQL with TypeORM
  2. Postgres with TypeORM
  3. MYSQL with Sequelize
  4. Postgres with Sequelize
  5. MYSQL with ObjectionJS
  6. Postgres with ObjectionJS
  7. MYSQL with KnexJS
  8. Postgres with KnexJS
  9. MongoDB with Mongoose

Tests

To run the test suite,

  1. first install the dependencies
  2. rename .env.sample to .env
  3. You can run docker-comose up or set your own connection URLs for postgres database and mysql database in .env
  4. run npm test:
$ npm install
$ npm test

Support and Suggestions

Feel free to open issues on github.