@japan-d2/error-handler

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

Usage no npm install needed!

<script type="module">
  import japanD2ErrorHandler from 'https://cdn.skypack.dev/@japan-d2/error-handler';
</script>

README

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