0.2.1 • Published 4 years ago

@cd2/error-box v0.2.1

Weekly downloads
-
License
MIT
Repository
-
Last release
4 years ago

Error Box

Create a consistent and descriptive errors setup for your applications.

npm i --save @cd2/error-box

or

yarn add @cd2/error-box

Usage

Testing

You can use the jest file!


Problem

  1. It should be easy to throw consistent errors across your application
  2. You should be able to catch the exact error you want without having to rely on matching error messages
  3. Errors should be serializable so they can be used between servers and clients
  4. They should provide details for the developer to help solve the issue
  5. They should be presentable to the end user

Usage

import { createErrorType, errorIs } from "@cd2/chucker"

// create an error type
const applicationError = createErrorType("my_application")

try {
  // throw an error 
  throw applicationError("validation", "Name must be present")
} catch (e) {

  // catch only the correct errors
  if (errorIs(e, applicationError("validation"))) {

    // show the developer the error
    console.error(e)


    // show the user
    showFlashMessage(e.toHumanString())
  }
}

You can subclass errors

const applicationError = createErrorType("my_app")
const validationError = applicationError.extend("validation")
const presenceValidationError = validationError.extend("presence")


const thrownError = presenceValidationError(null, "Name must be present")

errorIs(thrownError, applicationError) // => true
errorIs(thrownError, validationError) // => true
errorIs(thrownError, presenceValidationError) // => true

Serializable

const error = applicationError(null, "Message")

const json = error.toJSON()

// send over network

const parsedError = parseError(json)