fancy-error

1.0.0 • Public • Published

FancyError

The FancyError object extends the native Error object with a few features:

  • a context property, allowing for passing an object along with the error message
  • a caughtError property, allowing to wrap any Error-compatible object with your own FancyError and containing the original Error in the caughtError property. This also allows you to create an error chain with allowPassthrough = false or with differently named FancyErrors.
  • a fullMessage getter, allowing to get a message containing the messages from both this and the caughtError.

Because FancyError extends Error, stack traces work as usual.

Usage

The constructor has the following signature:

constructor(
  message: string,
  caughtError?: FancyError | Error,
  context?: { [key: string]: any },
  allowPassthrough: boolean = true
): FancyError

allowPassthrough determines whether an error object with the same prototype and name is passed or wrapped.

Examples

import FancyError from 'fancy-error';

const error = new FancyError('This is an error');
const passedError = new FancyError('This error lets `error` pass through', error);
const wrappedError = new FancyError('This error wraps `error`', error, null, false);

class OtherError extends FancyError {}
const otherError = new OtherError('This is a different error so `error` is not passed', error);

console.error(passedError.fullMessage);
// "This is an error"

console.error(wrappedError.fullMessage);
// "This error wraps `error`: [FancyError] This is an error"

console.error(otherError.fullMessage);
// "This is a different error so `error` is not passed: [FancyError] This is an error"

As shown in the example above, you can also create differently named versions of this error by extending it.

throw new FancyError('This is an error', null, { exampleData: true });
import FancyError from 'fancy-error';

const error = new Error('Something went wrong somewhere!');
const fancyError = new FancyError(
  'This error wraps a system error',
  error,
  { exampleData: true }
);

console.log(fancyError.name);
// "FancyError"

console.log(fancyError.message);
// "This error wraps a system error"

console.log(fancyError.fullMessage);
// "This error wraps a system error: [Error] Something went wrong somewhere!"

console.log(fancyError.context);
// { exampleData: true }

console.log(fancyError.caughtError.message);
// "Something went wrong somewhere!"

Development

npm i
npm run test
npm run build

Package Sidebar

Install

npm i fancy-error

Weekly Downloads

1

Version

1.0.0

License

ISC

Unpacked Size

5.48 kB

Total Files

5

Last publish

Collaborators

  • pwuts