@nick-bull/throws

0.0.1 • Public • Published

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 and type 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');
});

Readme

Keywords

none

Package Sidebar

Install

npm i @nick-bull/throws

Weekly Downloads

2

Version

0.0.1

License

MIT

Unpacked Size

51.6 kB

Total Files

19

Last publish

Collaborators

  • nick-bull