npm.io
2.2.2 • Published 3 years ago

@johngw/error

Licence
MIT
Version
2.2.2
Deps
1
Size
20 kB
Vulns
0
Weekly
0

@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')