fancy-error
v1.0.0
Published
Extended error object with context and chaining support
Downloads
10
Readme
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 anyError
-compatible object with your ownFancyError
and containing the originalError
in thecaughtError
property. This also allows you to create an error chain withallowPassthrough = false
or with differently namedFancyError
s. - a
fullMessage
getter, allowing to get a message containing the messages from boththis
and thecaughtError
.
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