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

1.0.2 • Public • Published

Ex-Error Build Status Coverage Status

An extendible error class for creating custom error.

Why Use This Package?

Custom error object is quite useful if you need to filter specific error type. You can read this article to get more context why custom error is very useful.

Example:

// With standard error object
try {
  // Normally one will throw an error
  throw new Error('Error on auth');
} catch (err) {
  // catch error in here
}
 
// With custom error object
try {
  throw new AuthError('Your password is missing');
} catch (err) {
  if (err instanceof AuthError) {
    // process error for AuthError
  } else {
    // process error for other than AuthError
  }
}

Using Package

import exError from 'ex-error';
// or
const exError = require('ex-error');
 
// creating default error object from standard Error class
const DefaultError = exError();
 
try {
  // adding error message
  throw new DefaultError('Error using default error');
} catch (e) {
  console.log(e.message); // -> 'Error using default error'
  console.log(e.name); // -> 'Error'
  console.log(instanceof DefaultError); // -> true
}
 
// creating custom error object
const CustomError = exError('CustomError');
 
try {
  // adding error message and custom properties
  throw new CustomError('Custom error', {
    code: 500,
    otherMessage: 'other message'
  });
} catch (e) {
  console.log(e.message); // -> 'Custom error'
  console.log(e.name); // -> 'CustomError'
  console.log(instanceof CustomError); // -> true
  console.log(e.code); // -> 500
  console.log(e.otherMessage); // -> 'other message'
}

One can also use it as class extension

import exError from 'ex-error';
 
const CustomError = exError('CustomError');
 
class UseCustomError extends CustomError {}
 
try {
  // adding error message and custom properties
  throw new UseCustomError('Custom error', {
    code: 500,
    otherMessage: 'other message'
  });
} catch (e) {
  console.log(e.message); // -> 'Custom error'
  console.log(e.name); // -> 'CustomError'
  console.log(instanceof CustomError); // -> true
  console.log(e.code); // -> 500
  console.log(e.otherMessage); // -> 'other message'
}

License

Licensed under the MIT License. You can find a copy of it in LICENSE.

Package Sidebar

Install

npm i ex-error

Weekly Downloads

4

Version

1.0.2

License

MIT

Unpacked Size

19.6 kB

Total Files

19

Last publish

Collaborators

  • computecoholic