@nick-bull/throws
v0.0.1
Published
Wraps a function with an error decorator
Downloads
3
Readme
Wraps a function with an error decorator
Installation
npm i @nick-bull/throws
Usage
Simply pass a decorator or error alongside the function you want to wrap.
The decorator can be:
- a string message for an error,
- an error object, which will have the cause error chained as a
chain
property, - a decorator object, that may contain a
message
andtype
property only,
The callback function may be asynchronous or synchronous; throws
will return a function of the same synchronicity.
import {throws} from 'nick-bull/throws'
const createUserError = {
type: 'user:create',
message: 'An error occurred creating the user',
};
const createUser = throws(createUserError, () => {
return explosiveFn();
});
// `findUser` will be asynchronous, matching the provided callback synchronicity
const UserNotFoundError = new Error('No such user');
const findUser = throws(UserNotFoundError, async (username) => {
return await find(username);
});
const fetchUserErrorMessage = 'An error occurred finding the user';
const fetchUser = throws(fetchUserErrorMessage, () => {
throw new Error('Not implemented');
});