errorish
For those times you have an error-ish but what you really want is an Error
If you come to find it useful, consider starring the project and/or following its author to show your ❤️
Install
npm install errorish
Use cases
There are essentially three use cases for errorish
:
Documentation
These are all of errorish
's functions -see docs:
ensure
ensures any
is an Error
, otherwise creating one -optionally, it can also have a normalization step, which is enabled by default.normalize
ensures an Error
has a message
, name
, and stack
properties -filling them if they're not defined.rejects
parses a help
string and returns an object with options, aliases, arguments, and descriptions.throws
parses a help
string and returns an object with options, aliases, arguments, and descriptions.
Options can be passed directly to these functions, though they will be merged in all cases with the defaults -you can use scope.set
to set these.
Additionally, you might want to create particular scopes
with a different set of default options depending on your use case.
Usage
Ensuring any
is an error -otherwise create it
Return an error from any error-ish
import { ensure } from 'errorish';
ensure(Error('Foo bar'));
ensure('Foo bar');
ensure({ message: 'Foo bar' });
ensure(10);
ensure(10, { allow: ['string', 'number'] });
ensure(10).source;
ensure(10, null, { foo: 'bar' }).data;
Throw or reject with an error-ish
throws
and rejects
run ensure
over your error-ish and throw or reject with it -these are just convenience functions over ensure
:
import { rejects } from 'errorish';
Promise.reject(10).catch(rejects)
Promise.reject(10).catch(err => rejects(err, { case: false }));
Normalizing errors
Normalization is performed by default by ensure
, but it can also be run independently:
import { normalize } from 'errorish';
normalize(Error());
normalize(Error(), { message: 'Foo bar' });
Catching and throwing errors to be made public
import { Errorish, scope } from 'errorish';
const ish = scope.set('ish', { Error: Errorish, allow: [] });
function authorize() {
throw Error(`Error with details I'd rather not expose`);
}
function example() {
try {
authorize();
} catch (err) {
throw ish.ensure(
err,
{ message: `Authorization for example failed` },
{ code: 401 }
);
}
}
function server() {
try {
example();
} catch (err) {
throw ish.ensure(err, { message: 'Server failed' }, { code: 500 });
}
}
try {
server();
} catch (e) {
console.log(e.message);
console.log(e.data);
console.log(e.source);
}