@johngw/error
TypeScript icon, indicating that this package has built-in type declarations

2.2.2 • Public • Published

@johngw/error

Error handling

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

An adaptation of assertNever 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

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

Passing arguments example

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

Type catching

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.

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

Readme

Keywords

none

Package Sidebar

Install

npm i @johngw/error

Weekly Downloads

220

Version

2.2.2

License

MIT

Unpacked Size

20.3 kB

Total Files

23

Last publish

Collaborators

  • johngeorgewright