
Convert errors to/from plain objects.
Features
Example
import { serialize, parse } from 'error-serializer'
const error = new TypeError('example')
const errorObject = serialize(error)
const errorString = JSON.stringify(errorObject)
const newErrorObject = JSON.parse(errorString)
const newError = parse(newErrorObject)
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') }])
serialize([{ error: new Error('test') }], { shallow: true })
normalize
Type: boolean
Default: false
Convert errorInstance
to an Error
instance if it is not one.
serialize('example')
serialize('example', { normalize: true })
beforeSerialize(errorInstance)
Type: (errorInstance) => void
Called before serializing each errorInstance
.
afterSerialize(errorInstance)
Type: (errorInstance) => void
Called after serializing each errorInstance
.
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
const errorObject = serialize(new CustomError('example'))
const error = parse(errorObject, { classes: { CustomError } })
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 }])
parse([{ error: errorObject }], { shallow: true })
normalize
Type: boolean
Default: false
Convert errorObject
to an error plain object if it is not one.
parse('example')
parse('example', { normalize: true })
beforeParse(errorObject)
Type: (errorObject) => void
Called before parsing each errorObject
.
afterParse(errorObject)
Type: (errorObject) => void
Called after parsing each errorObject
.
Usage
JSON safety
Error plain objects are always
safe to serialize with JSON.
const error = new Error('example')
error.cycle = error
serialize(error).cycle
error.toJSON()
serialize()
can be used as
error.toJSON()
.
class CustomError extends Error {
toJSON() {
return serialize(this)
}
}
const error = new CustomError('example')
error.toJSON()
JSON.stringify(error)
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)
const newErrorObject = load(errorYamlString)
const newError = parse(newErrorObject)
Additional error properties
const error = new TypeError('example')
error.prop = true
const errorObject = serialize(error)
console.log(errorObject.prop)
const newError = parse(errorObject)
console.log(newError.prop)
Events
const error = new Error('test')
error.date = new Date()
const errors = [error]
const errorObjects = serialize(errors, {
beforeSerialize(errorArg) {
errorArg.date = errorArg.date.toString()
},
afterSerialize(errorArg) {
errorArg.date = new Date(errorArg.date)
},
})
console.log(errorObjects[0].date)
const newErrors = parse(errorObjects, {
beforeParse(errorObjectArg) {
errorObjectArg.date = new Date(errorObjectArg.date)
},
afterParse(errorObjectArg) {
errorObjectArg.date = errorObjectArg.date.toString()
},
})
console.log(newErrors[0].date)
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)
const newError = parse(errorObject)
Constructors
By default, when an error with custom classes
is parsed, its
constructor is not called. In most cases, this is not a problem since any
property previously set by that constructor is still preserved, providing it is
serializable and enumerable.
However, the error.constructorArgs
property can be set to call the constructor
with those arguments. It it throws, Error
will be used as a fallback error
class.
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)
const newError = parse(errorObject, { classes: { CustomError } })
Related projects
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!