2.0.0 • Published 3 years ago

throw-utils v2.0.0

Weekly downloads
17
License
MIT
Repository
github
Last release
3 years ago

throw-utils

Actions Status npm license

Tiny helpers for error throwing.

Installation

npm i throw-utils

Use Cases

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

    import { throwError } from 'throw-utils';
    
    - if (!process.env.FOO) {
    -   throw new Error('FOO is not defined');
    - }
    - const foo = process.env.FOO;
    
    + const foo = process.env.FOO || throwError('FOO is not defined');
  2. Return result from function or throw error if result is empty:

    const { throwIf } = require('throw-utils');
    
    function foo(a) {
    - if (!a) {
    -   throw new Error('Parameter a is required.');
    - }
    - return result;
    
    + return result || throwError('Empty result');
    }
  3. Check function parameters in single line:

    import { throwIf } from 'throw-utils';
    
    function f(a) {
    - if (!a) {
    -   throw new Error('Parameter a is required.');
    - }
    
    + throwIf(!a, 'Parameter a is required.');
    }

API

throwError

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

FunctionType
throwError(msg: ErrorLike) => never

throwIf

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

FunctionType
throwIf(condition: unknown, msg: ErrorLike) => void

toError

Converts anything to Error.

FunctionType
toError(msg: ErrorLike) => Error

License

MIT @ Vitaliy Potapov

2.0.0

3 years ago

1.2.0

5 years ago

1.2.1

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.0

5 years ago

0.1.3

6 years ago

0.1.2

6 years ago

0.1.1

7 years ago