Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/vitalets/throw-utils
Helpers for error throwing
https://github.com/vitalets/throw-utils
throw throw-errors
Last synced: 2 months ago
JSON representation
Helpers for error throwing
- Host: GitHub
- URL: https://github.com/vitalets/throw-utils
- Owner: vitalets
- Created: 2018-11-22T17:46:49.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2022-10-21T11:15:25.000Z (about 2 years ago)
- Last Synced: 2024-09-14T02:55:20.206Z (4 months ago)
- Topics: throw, throw-errors
- Language: TypeScript
- Homepage:
- Size: 382 KB
- Stars: 5
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# throw-utils
[![Actions Status](https://github.com/vitalets/throw-utils/workflows/autotests/badge.svg)](https://github.com/vitalets/throw-utils/actions)
[![npm](https://img.shields.io/npm/v/throw-utils.svg)](https://www.npmjs.com/package/throw-utils)
[![license](https://img.shields.io/npm/l/throw-utils.svg)](https://www.npmjs.com/package/throw-utils)Tiny helpers for error throwing.
- [Installation](#installation)
- [Use Cases](#use-cases)
- [API](#api)
- [throwError](#throwerror)
- [throwIf](#throwif)
- [toError](#toerror)
- [License](#license)## Installation
```bash
npm i throw-utils
```## Use Cases
1. Assign value or throw error if value is empty:
```diff
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:
```diff
import { throwIf } from '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:
```diff
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.
| Function | Type |
| ---------- | ---------- |
| `throwError` | `(msg: ErrorLike) => never` |### throwIf
Conditionally throws error. Convenient replacement of `if...throw` block with one-liner:
| Function | Type |
| ---------- | ---------- |
| `throwIf` | `(condition: unknown, msg: ErrorLike) => void` |### toError
Converts anything to Error.
| Function | Type |
| ---------- | ---------- |
| `toError` | `(msg: ErrorLike) => Error` |## License
MIT @ [Vitaliy Potapov](https://github.com/vitalets)