1.0.0 • Published 4 years ago
@bumped-inc/unknown-error v1.0.0
@bumped-inc/unknown-error
Convert any value into an Error
This is a simple mechanism for converting something which may or may not be an
Error
to something that definitely is an Error
. This can be useful when
dealing with third-party libraries that do not throw
or reject
with Error
s
as one would normally expect.
This has no dependencies and can be used within Node, browsers, and react-native.
If the value passed to asError
is not an instance of Error
, an
UnknownError
will be returned. If needed, one can access .originalValue
on
an UnknownError
to retrieve the original value, which can be useful especially
if the error represents an unsuccessful Response or otherwise has useful
information. UnknownError
is intentionally unopinionated.
Usage
import { asError, UnknownError, isUnknownError } from '@bumped-inc/unknown-error';
asError(new Error('oh no!')) //=> same value, [Error: oh no!]
asError({ message: 'not a real error' }) //=> [UnknownError: A non-Error value was thrown]
isUnknownError(asError('oh no')) //=> true
asError('oh no') instanceof UnknownError //=> true
someAsyncFn()
.catch((maybeError) => {
const error: Error = asError(maybeError);
doSomethingWith(error);
});
try {
doSomethingDangerous();
} catch (maybeError) {
const error: Error = asError(maybeError);
doSomethingWith(error);
}
1.0.0
4 years ago