throw-utils

Helpers for error throwing

Usage no npm install needed!

<script type="module">
  import throwUtils from 'https://cdn.skypack.dev/throw-utils';
</script>

README

throw-utils

Actions Status npm license

One-liner helpers for convenient error throwing.

Installation

npm i throw-utils

Usecases

  1. Return value or throw error if value is empty:

    const { throwError } = require('throw-utils');
    
    function foo() {
      // ...
     
    - if (result) {
    -   return result;
    - } else {
    -   throw new Error('Empty result');
    - }
     
    + return result || throwError('Empty result');
    }
    
  2. Throw error in arrow function one-liner:

    - const fn = () => { throw new Error('foo'); };
    
    + const fn = () => throwError('foo');
    
  3. Throw error in conditional one-liner:

    const { throwIf } = require('throw-utils');
    
    function foo(a, b) {
    - if (!a) {
    -   throw new Error('Parameter a is required.');
    - }
    - if (!b) {
    -   throw new Error('Parameter b is required.');
    - }
    
    + throwIf(!a, 'Parameter a is required.');
    + throwIf(!b, 'Parameter b is required.');
    }   
    
  4. Throw error in next tick:

    const { throwAsync } = require('throw-utils');
    
    - setTimeout(() => {
    -   throw new Error('foo');
    - }, 0);
    
    + throwAsync('foo');
    

API

throwError(error)

Throws new error. Allows simple usage of throw in expressions and arrow functions.

Kind: global function
Params

  • error String | Error

Example

const { throwError } = require('throw-utils');

// usage in expression
const foo = value || throwError('Error');

// usage in arrow function
setTimeout(() => throwError('Error'), 1000);

throwIf(condition, error)

Conditionally throws error. Convenient replacement of if...throw block with one-liner:

Kind: global function
Params

  • condition *
  • error String | Error | function

Example

const { throwIf } = require('throw-utils');

throwIf(foo > 10, 'my error');
throwIf(foo > 10, new Error('my error'));
throwIf(foo > 10, () => `my error: ${JSON.stringify(data)}`); // lazy calculated Error

throwAsync(error)

Throws error in next event loop tick. Useful to throw error out of promise chain.

Kind: global function
Params

  • error String | Error

Example

const { throwAsync } = require('throw-utils');

Promise.resolve()
  .then(...)
  .catch(e => throwAsync(e));

toError(value) ⇒ Error

Converts anything to Error.

Kind: global function
Params

  • value String | Error

License

MIT @ Vitaliy Potapov