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

0.0.4 • Public • Published

error-handler

A type-safe error handling library that can automatically re-throw unhandled errors.

install

npm install @japan-d2/error-handler

or

yarn add @japan-d2/error-handler

usage

Error Class Designing

NOTE: It does not work when transpiring to es5 or lower.

class BaseError extends Error {
  constructor () {
    super(code)
    this.name = this.constructor.name
  }
}

class NetworkError extends BaseError {}

Handling

import { handleExpectedErrors } from '@japan-d2/error-handler'

try {
  throw new NetworkError()
} catch (error) {
  handleExpectedErrors(error, ({ handleError }) => {
    handleError(Error, (e) => {
      // only first matched handler will be called
      expectedToCall()
    })
    handleError(NetworkError, (e) => {
      doNotCall()
    })
  })
}

Pass-Through

import { handleExpectedErrors } from '@japan-d2/error-handler'

try {
  throw new NetworkError()
} catch (error) {
  handleExpectedErrors(error, ({ handleError, pass }) => {
    handleError(Error, (e) => {
      // umm... I give up handling.
      pass()
    })
    handleError(NetworkError, (e) => {
      // to be called
      expectedToCall()
    })
  })
}

Result

Returning a value in handleError will also propagate to the return value of handleExpectedErrors.

import { handleExpectedErrors } from '@japan-d2/error-handler'

try {
  throw new NetworkError()
} catch (error) {
  return handleExpectedErrors(error, ({ handleError, pass }) => {
    handleError(Error, (e) => {
      return {
        statusCode: 500,
        body: JSON.stringify({
          message: e.message,
        })
      }
    })
  })
}

Options

throwIfUnhandled: boolean (default = true)

import { handleExpectedErrors } from '@japan-d2/error-handler'

try {
  (undefined as any).hello()
} catch (error) {
  handleExpectedErrors(error, ({ handleError }) => {
    handleError(NetworkError, (e) => {
      console.error(e)
    })
  }, { throwIfUnhandled: false })

  // please handle manually...
}

license

MIT

Readme

Keywords

Package Sidebar

Install

npm i @japan-d2/error-handler

Weekly Downloads

2

Version

0.0.4

License

MIT

Unpacked Size

6.13 kB

Total Files

5

Last publish

Collaborators

  • uneco
  • tatat