Package Exports
- error-serializer
Readme
Convert errors to/from plain objects.
Features
- Ensures errors are safe to serialize with JSON
- Can be used as
error.toJSON()
- Deep serialization/parsing
- Custom serialization/parsing (e.g. YAML or
process.send()
) - Keeps both native (
TypeError
, etc.) and custom error classes - Preserves errors' additional properties
- Can keep constructor's arguments
- Works recursively with
error.cause
andAggregateError
- Normalizes invalid errors
- Safe: this never throws
Example
import { serialize, parse } from 'error-serializer'
const error = new TypeError('example')
const errorObject = serialize(error)
// Plain object: { name: 'TypeError', message: 'example', stack: '...' }
const errorString = JSON.stringify(errorObject)
const newErrorObject = JSON.parse(errorString)
const newError = parse(newErrorObject)
// Error instance: 'TypeError: example ...'
Install
npm install error-serializer
This package works in both Node.js >=14.18.0 and
browsers.
It is an ES module and must be loaded using
an import
or import()
statement,
not require()
.
API
serialize(errorInstance, options?)
errorInstance
any
options
Options?
Return value: object
Convert an Error
instance into a plain object.
Options
Object with the following optional properties.
shallow
Type: boolean
Default: false
Unless this option is true
, nested errors are also serialized. They can be
inside other errors, plain objects or arrays.
serialize([{ error: new Error('test') }]) // [{ error: { name: 'Error', ... } }]
serialize([{ error: new Error('test') }], { shallow: true }) // [{ error: Error }]
normalize
Type: boolean
Default: false
Convert errorInstance
to an Error
instance if it is not one.
serialize('example') // 'example'
serialize('example', { normalize: true }) // { name: 'Error', message: 'example', ... }
parse(errorObject, options?)
errorObject
any
options
Options?
Return value: Error
Convert an error plain object into an Error
instance.
Options
Object with the following optional properties.
classes
Type: object
Custom error classes to keep when parsing.
- Each key is an
errorObject.name
. - Each value is the error class to use. The constructor will be called with a
single
message
argument. It it throws,Error
will be used as the error class instead.
const errorObject = serialize(new CustomError('example'))
// `CustomError` class is kept
const error = parse(errorObject, { classes: { CustomError } })
// Map `CustomError` to another class
const otherError = parse(errorObject, { classes: { CustomError: TypeError } })
shallow
Type: boolean
Default: false
Unless this option is true
, nested error plain objects are also parsed.
const errorObject = serialize(new Error('test'))
parse([{ error: errorObject }])
// [{ error: Error }]
parse([{ error: errorObject }], { shallow: true })
// [{ error: { name: 'Error', ... } }]
normalize
Type: boolean
Default: false
Convert errorObject
to an error plain object if it is not one.
parse('example') // 'example'
parse('example', { normalize: true }) // Error: example
Usage
JSON safety
Error plain objects are always safe to serialize with JSON.
const error = new Error('example')
error.cycle = error
// Cycles make `JSON.stringify()` throw, so they are removed
serialize(error).cycle // undefined
error.toJSON()
serialize()
can be used as
error.toJSON()
.
class CustomError extends Error {
/* constructor(...) { ... } */
toJSON() {
return serialize(this)
}
}
const error = new CustomError('example')
error.toJSON()
// { name: 'CustomError', message: 'example', stack: '...' }
JSON.stringify(error)
// '{"name":"CustomError","message":"example","stack":"..."}'
Custom serialization/parsing
Errors are converted to/from plain objects, not strings. This allows any serialization/parsing logic to be performed.
import { dump, load } from 'js-yaml'
const error = new Error('example')
const errorObject = serialize(error)
const errorYamlString = dump(errorObject)
// name: Error
// message: example
// stack: Error: example ...
const newErrorObject = load(errorYamlString)
const newError = parse(newErrorObject) // Error: example
Additional error properties
const error = new TypeError('example')
error.prop = true
const errorObject = serialize(error)
console.log(errorObject.prop) // true
const newError = parse(errorObject)
console.log(newError.prop) // true
error.cause
and AggregateError
const innerErrors = [new Error('one'), new Error('two')]
const cause = new Error('three')
const error = new AggregateError(innerErrors, 'four', { cause })
const errorObject = serialize(error)
// {
// name: 'AggregateError',
// message: 'four',
// stack: '...',
// cause: { name: 'Error', message: 'three', stack: '...' },
// errors: [{ name: 'Error', message: 'one', stack: '...' }, ...],
// }
const newError = parse(errorObject)
// AggregateError: four
// [cause]: Error: three
// [errors]: [Error: one, Error: two]
Constructor's arguments
parse()
calls new ErrorClass(message, {})
by
default. This works well with regular error classes.
When more advanced error classes
are used, the constructor's
arguments can be explicitly set as an error.constructorArgs
property.
class CustomError extends Error {
constructor(prefix, message) {
super(`${prefix} - ${message}`)
this.constructorArgs = [prefix, message]
}
}
CustomError.prototype.name = 'CustomError'
const error = new CustomError('Prefix', 'example')
const errorObject = serialize(error)
// This calls `new CustomError('Prefix', 'example')`
const newError = parse(errorObject, { classes: { CustomError } })
Related projects
modern-errors
: Handle errors like it's 2022 🔮modern-errors-serialize
: Serialize/parse errorserror-custom-class
: Create one error classerror-class-utils
: Utilities to properly create error classesnormalize-exception
: Normalize exceptions/errorsis-error-instance
: Check if a value is anError
instancemerge-error-cause
: Merge an error with itscause
set-error-class
: Properly update an error's classset-error-message
: Properly update an error's messageset-error-props
: Properly update an error's propertieserror-cause-polyfill
: Polyfillerror.cause
handle-cli-error
: 💣 Error handler for CLI applications 💥safe-json-value
: ⛑️ JSON serialization should never faillog-process-errors
: Show some ❤ to Node.js process errors
Support
For any question, don't hesitate to submit an issue on GitHub.
Everyone is welcome regardless of personal background. We enforce a Code of conduct in order to promote a positive and inclusive environment.
Contributing
This project was made with ❤️. The simplest way to give back is by starring and sharing it online.
If the documentation is unclear or has a typo, please click on the page's Edit
button (pencil icon) and suggest a correction.
If you would like to help us fix a bug or add a new feature, please check our guidelines. Pull requests are welcome!
ehmicky 💻 🎨 🤔 📖 |
Pedro Augusto de Paula Barbosa 🐛 📖 |