New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

error-serializer

Package Overview
Dependencies
Maintainers
1
Versions
29
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

error-serializer

Convert errors to/from plain objects

  • 3.7.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2.8K
decreased by-13.11%
Maintainers
1
Weekly downloads
 
Created
Source

Node Browsers TypeScript Codecov Minified size Twitter Medium

Convert errors to/from plain objects.

Features

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 } })

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
ehmicky

💻 🎨 🤔 📖
Pedro Augusto de Paula Barbosa
Pedro Augusto de Paula Barbosa

🐛 📖

Keywords

FAQs

Package last updated on 11 Nov 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc