@cd2/error-box
v0.2.1
Published
Create a consistent and descriptive errors setup for your applications.
Downloads
42
Readme
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
- It should be easy to throw consistent errors across your application
- You should be able to catch the exact error you want without having to rely on matching error messages
- Errors should be serializable so they can be used between servers and clients
- They should provide details for the developer to help solve the issue
- 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)