Convert errors to/from plain objects.
- Ensures errors are safe to serialize with JSON
- Can be used as
error.toJSON() - Deep serialization/parsing, including transforming
- 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.causeandAggregateError - Normalizes invalid errors
- Safe: this never throws
import { parse, serialize } 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 ...'npm install error-serializerThis package works in both Node.js >=18.18.0 and browsers.
This is an ES module. It must be loaded using
an import or import() statement,
not require(). If TypeScript is used, it must be configured to
output ES modules,
not CommonJS.
errorInstance any
options Options?
Return value: ErrorObject
Convert an Error instance into a plain object.
Object with the following optional properties.
Type: boolean
Default: false
Unless this option is true, nested errors are also serialized. They can be
inside other errors, plain objects or arrays.
const error = new Error('example')
error.inner = new Error('inner')
serialize(error).inner // { name: 'Error', message: 'inner', ... }
serialize(error, { shallow: true }).inner // Error: inner ...Type: boolean
Default: false
By default, when the argument is not an Error instance, it is converted to
one. If this option is true, it is kept as is instead.
serialize('example') // { name: 'Error', message: 'example', ... }
serialize('example', { loose: true }) // 'example'Type: string[]
Only pick specific properties.
serialize(error, { include: ['message'] }) // { message: 'example' }Type: string[]
Omit specific properties.
serialize(error, { exclude: ['stack'] }) // { name: 'Error', message: 'example' }Type: (errorObject, errorInstance) => void
Transform each error plain object.
errorObject is the error after serialization. It must be directly mutated.
errorInstance is the error before serialization.
errorObject any
options Options?
Return value: Error
Convert an error plain object into an Error instance.
Object with the following optional properties.
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'))
// `CustomError` class is kept
const error = parse(errorObject, { classes: { CustomError } })
// Map `CustomError` to another class
const otherError = parse(errorObject, { classes: { CustomError: TypeError } })Type: boolean
Default: false
Unless this option is true, nested error plain objects are also parsed. They
can be inside other errors, plain objects or arrays.
const error = new Error('example')
error.inner = new Error('inner')
const errorObject = serialize(error)
parse(errorObject).inner // Error: inner ...
parse(errorObject, { shallow: true }).inner // { name: 'Error', message: ... }Type: boolean
Default: false
By default, when the argument is not an error plain object, it is converted to
one. If this option is true, it is kept as is instead.
parse('example') // Error: example
parse('example', { loose: true }) // 'example'Type: (constructorArgs, errorObject, ErrorClass) => void
Transform the arguments passed to each new Error().
constructorArgs is the array of arguments. Usually, constructorArgs[0] is
the
error message
and constructorArgs[1] is the
constructor options object.
constructorArgs must be directly mutated.
errorObject is the error before parsing. ErrorClass is its
class.
Type: (errorInstance, errorObject) => void
Transform each Error instance.
errorInstance is the error after parsing. It must be directly mutated.
errorObject is the error before parsing.
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 // undefinedserialize() 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":"..."}'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: exampleconst error = new TypeError('example')
error.prop = true
const errorObject = serialize(error)
console.log(errorObject.prop) // true
const newError = parse(errorObject)
console.log(newError.prop) // trueconst error = new Error('example')
error.prop = true
const errorObject = serialize(error, { include: ['name', 'message', 'stack'] })
console.log(errorObject.prop) // undefined
console.log(errorObject) // { name: 'Error', message: 'example', stack: '...' }const error = new Error('example')
const errorObject = serialize(error, { exclude: ['stack'] })
console.log(errorObject.stack) // undefined
console.log(errorObject) // { name: 'Error', message: 'example' }The loose option can be used to deeply serialize/parse objects and
arrays.
const error = new Error('example')
const deepArray = serialize([{}, { error }], { loose: true })
const jsonString = JSON.stringify(deepArray)
const newDeepArray = JSON.parse(jsonString)
const newError = parse(newDeepArray, { loose: true })[1].error // Error: exampleconst errors = [new Error('test secret')]
errors[0].date = new Date()
const errorObjects = serialize(errors, {
loose: true,
// Serialize `Date` instances as strings
transformObject: (errorObject) => {
errorObject.date = errorObject.date.toString()
},
})
console.log(errorObjects[0].date) // Date string
const newErrors = parse(errorObjects, {
loose: true,
// Transform error message
transformArgs: (constructorArgs) => {
constructorArgs[0] = constructorArgs[0].replace('secret', '***')
},
// Parse date strings as `Date` instances
transformInstance: (error) => {
error.date = new Date(error.date)
},
})
console.log(newErrors[0].message) // 'test ***'
console.log(newErrors[0].date) // `Date` instanceconst 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]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)
// This calls `new CustomError('Prefix', 'example')`
const newError = parse(errorObject, { classes: { CustomError } })modern-errors: Handle errors in a simple, stable, consistent waymodern-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 anErrorinstancemerge-error-cause: Merge an error with itscauseset-error-class: Properly update an error's classset-error-message: Properly update an error's messagewrap-error-message: Properly wrap an error's messageset-error-props: Properly update an error's propertiesset-error-stack: Properly update an error's stackerror-cause-polyfill: Polyfillerror.causehandle-cli-error: π£ Error handler for CLI applications π₯beautiful-error: Prettify error messages and stackssafe-json-value: βοΈ JSON serialization should never faillog-process-errors: Show some β€ to Node.js process errorserror-http-response: Create HTTP error responseswinston-error-format: Log errors with Winston
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.
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 π π |
JasonKleban π» π |