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

  • 4.0.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', ... }
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'))
// `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
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

// 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

Events

const error = new Error('test')
error.date = new Date()
const errors = [error]

const errorObjects = serialize(errors, {
  // Serialize `Date` instances as strings
  beforeSerialize(errorArg) {
    errorArg.date = errorArg.date.toString()
  },
  // Restore `error.date` after serializing it
  afterSerialize(errorArg) {
    errorArg.date = new Date(errorArg.date)
  },
})
console.log(errorObjects[0].date) // Date string

const newErrors = parse(errorObjects, {
  // Parse date strings as `Date` instances
  beforeParse(errorObjectArg) {
    errorObjectArg.date = new Date(errorObjectArg.date)
  },
  // Restore `errorObject.date` after parsing
  afterParse(errorObjectArg) {
    errorObjectArg.date = errorObjectArg.date.toString()
  },
})
console.log(newErrors[0].date) // `Date` instance

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]

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)
// 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 18 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