customizable-error
TypeScript icon, indicating that this package has built-in type declarations

0.1.3 • Public • Published

Customizable error

Description

Let you define an error with custom fields to pass extra informations with message

Installation

npm i --save customizable-error

Using the factory

import { customErrorFactory } from 'customizable-error';

// some code that throw an error
(req, res, next) => {
  next(
    customErrorFactory({
      name: 'SuperError',
      code: 'SUPER_ERROR',
      message: 'this is an error message',
      status: 500,
      foo: 'bar',
      baz: 'bat',
    }),
  );
}

// some code that handles the error

const errorHandler = (err, req, res, next) => {
  res.status(err.getStatus()).json({
    success: false,
    message: err.getMessage(), // 'this is an error message'
    code: err.getCode(), // 'SUPER_ERROR'
    data: err.getExtraFields(), // { foo: 'bar', baz: 'bat' }
  });
};

Extending the class

import { CustomError, ErrorOptions } from 'customizable-error';

class SuperError extends CustomError {
  constructor() {
    super({
      name: 'SuperError',
      code: 'SUPER_ERROR',
      message: 'this is an error message',
      status: 500,
      foo: 'bar',
      baz: 'bat',
    })
  }
}

// some code that throw an error
(req, res, next) => {
  next(SuperError());
}

// some code that handles the error
const errorHandler = (err, req, res, next) => {
  res.status(err.getStatus()).json({
    success: false,
    message: err.getMessage(), // 'this is an error message'
    code: err.getCode(), // 'SUPER_ERROR'
    data: err.getExtraFields(), // { foo: 'bar', baz: 'bat' }
  });
};

Dependents (2)

Package Sidebar

Install

npm i customizable-error

Weekly Downloads

1

Version

0.1.3

License

MIT

Unpacked Size

20.5 kB

Total Files

16

Last publish

Collaborators

  • chipp972