npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

error-serializer

v7.0.0

Published

Convert errors to/from plain objects

Downloads

14,311

Readme

Node Browsers TypeScript Codecov Minified size Mastodon Medium

Convert errors to/from plain objects.

Hire me

Please reach out if you're looking for a Node.js API or CLI engineer (11 years of experience). Most recently I have been Netlify Build's and Netlify Plugins' technical lead for 2.5 years. I am available for full-time remote positions.

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 >=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.

API

serialize(errorInstance, options?)

errorInstance any
options Options?
Return value: ErrorObject

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.

const error = new Error('example')
error.inner = new Error('inner')
serialize(error).inner // { name: 'Error', message: 'inner', ... }
serialize(error, { shallow: true }).inner // Error: inner ...

loose

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'

beforeSerialize(errorInstance)

Type: (errorInstance) => void

Called before serializing each errorInstance.

afterSerialize(errorInstance, errorObject)

Type: (errorInstance, errorObject) => 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. 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: ... }

loose

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'

beforeParse(errorObject)

Type: (errorObject) => void

Called before parsing each errorObject.

afterParse(errorObject, errorInstance)

Type: (errorObject, errorInstance) => 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

Deep serialization/parsing

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: example

Events

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

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

const newErrors = parse(errorObjects, {
  loose: true,
  // Parse date strings as `Date` instances
  beforeParse: (errorObject) => {
    errorObject.date = new Date(errorObject.date)
  },
  // Restore `errorObject.date` after parsing
  afterParse: (errorObject, error) => {
    errorObject.date = errorObject.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 } })

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!