# @johngw/error

> JS/TS Error handling utilities.

Latest version **2.2.2** (published 2023-05-19) · MIT license · 0 weekly downloads

## Install

```sh
npm install @johngw/error
pnpm add @johngw/error
yarn add @johngw/error
bun add @johngw/error
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 2.2.2 |
| Published | 2023-05-19 |
| First published | 2021-03-10 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 1 |
| Unpacked size | 19.8 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | John Wright <johngeorge.wright@gmail.com> |
| Maintainers | johngeorgewright |

## Links

- npm: https://www.npmjs.com/package/@johngw/error
- Homepage: https://github.com/johngeorgewright/js-util#readme
- Issues: https://github.com/johngeorgewright/js-util/issues
- npm.io page: https://npm.io/package/@johngw/error

## Dependencies (1)

- [tslib](https://npm.io/package/tslib.md) 2.5.2

## Recent versions

- 2.2.2 (latest) — 2023-05-19
- 2.2.1 — 2023-05-10
- 2.2.0 — 2021-10-20
- 2.1.1 — 2021-07-13
- 2.1.0 — 2021-07-11
- 2.0.1 — 2021-06-09
- 2.0.0 — 2021-06-07
- 1.3.8 — 2021-05-28
- 1.2.0 — 2021-04-01
- 1.1.0 — 2021-03-31
- 1.0.0 — 2021-03-10
- 0.0.0 — 2021-03-10

## README

# @johngw/error

Error handling

## `assertNever<T, M extends string>(message: M, type: T): CompileError<[M, T]>`

An adaptation of [assertNever](https://github.com/aikoven/assert-never#readme) that provides the reader with a custom type error.

## `tryCatch`

Try/catch as an expression that handles error types. **NOTE: This will not work as expected if compiled to anything lower than ES6 syntax.**

### Simple example

```typescript
const result = tryCatch(
  () => {
    throw new Error('foobar')
  },
  (error) => error.message
)
expect(result).toBe('foobar')
```

### Passing arguments example

```typescript
const result = tryCatch(
  (a, b) => {
    throw new Error(`${a}${b}`)
  },
  (error) => error.message,
  'foo',
  'bar'
)
expect(result).toBe('foobar')
```

### Type catching

```typescript
import { except, tryCatch } from '@johngw/error'

const result = tryCatch(() => {
  throw new ReferenceError('Bad reference')
}, [
  except(ReferenceError, (error) => 'On no, bad reference'),
  (error) => error.message,
])
expect(result).toBe('On no, bad reference')
```

### Promises example

This will resolve/catch promise errors too.

```typescript
const result = await tryCatch(
  async () => {
    throw new Error('foobar')
  },
  async (error) => error.message
)
expect(result).toBe('foobar')
```

---
_Source: https://npm.io/package/@johngw/error · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
