2.0.0 • Published 1 year ago
errorish v2.0.0
Errorish
When you have an error-ish but what you really want is an Error.
Install
Use cases
There are three main use cases for Errorish:
- You need to make sure an
Errorhas amessage,name, andstackproperties. - You need to make sure any object is actually an error, as expected.
- You want to extend the
Errorclass to store an identifyinglabel, a sourceerror, and/or associateddata.
Usage
Exceptionis an Error extending class with additionallabel,erroranddatafields.- Utils:
ensureensuresanyis anError, otherwise creating one -it can optionally include a normalization step, enabled by default.normalizeensures anErrorhas amessage,name, andstackproperties -filling them if they're not defined.capturerunsError.captureStackTraceif running inV8to clean up the error stack trace.
Exception
See documentation for Exception.
Exception is an Error extending class that can store an identifying label, the source error that caused it and/or additional associated data. Exception also comes with several static and instance methods.
import { Exception } from 'errorish';
try {
try {
throw new Error('Source');
} catch (err) {
// throws with label
throw new Exception(['label', 'message'], err, { code: 401 });
}
} catch (err) {
// throws without label
throw new Exception(err.message, err, { code: 500 })
}Utils
ensure
Ensure will return its first argument if an instance of Error is passed as such, otherwise instantiating and returning an Exception.
import { ensure } from 'errorish';
ensure('foo'); // Error: foo
ensure(new Error('foo')); // Error: foo
ensure({ message: 'foo' }); // Error: foonormalize
See documentation for normalize.
Normalization fills an error's message, name, and stack property when empty. It's performed by default by ensure, but it can also be run independently.
import { normalize } from 'errorish';
normalize(new Error()); // Error: An error occurred
normalize(new Error(), { message: 'Foo bar' }); // Error: Foo barcapture
See documentation for capture.
Captures the stack trace on Node and Chromium browsers.
import { capture } from 'errorish';
capture(new Error());