Tiny helpers for error throwing.
npm i throw-utils-
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'); -
Return result from function or throw error if result is empty:
import { throwIf } from 'throw-utils'; function foo(a) { - if (!a) { - throw new Error('Parameter a is required.'); - } - return result; + return result || throwError('Empty result'); } -
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.'); }
Throws new error. Allows simple usage of throw in expressions and arrow functions.
| Function | Type |
|---|---|
throwError |
(msg: ErrorLike) => never |
Conditionally throws error. Convenient replacement of if...throw block with one-liner:
| Function | Type |
|---|---|
throwIf |
(condition: unknown, msg: ErrorLike) => void |
Converts anything to Error.
| Function | Type |
|---|---|
toError |
(msg: ErrorLike) => Error |
MIT @ Vitaliy Potapov