Giter Site home page Giter Site logo

ehmicky / modern-errors-serialize Goto Github PK

View Code? Open in Web Editor NEW
9.0 2.0 0.0 4.7 MB

`modern-errors` plugin to serialize/parse errors.

License: MIT License

JavaScript 87.75% TypeScript 12.25%
browser error error-handler error-handling error-monitoring javascript json library modern-errors modern-errors-plugin

modern-errors-serialize's Introduction

modern-errors logo

Node Browsers TypeScript Codecov Minified size Mastodon Medium

modern-errors plugin to serialize/parse errors.

This adds BaseError.serialize() and BaseError.parse() to serialize/parse 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

Adding the plugin to modern-errors.

import ModernError from 'modern-errors'

import modernErrorsSerialize from 'modern-errors-serialize'

export const BaseError = ModernError.subclass('BaseError', {
  plugins: [modernErrorsSerialize],
})
// ...

Serializing errors to plain objects.

const error = new ExampleError('message', { props: { filePath } })

const errorObject = BaseError.serialize(error)
// { name: 'ExampleError', message: 'message', stack: '...', filePath: '...' }
const errorString = JSON.stringify(errorObject)
// '{"name":"ExampleError",...}'

Parsing errors from plain objects.

const newErrorObject = JSON.parse(errorString)
const newError = BaseError.parse(newErrorObject)
// ExampleError: message
//     at ...
//   filePath: '...'

Install

npm install modern-errors-serialize

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

modernErrorsSerialize

Type: Plugin

Plugin object to pass to the plugins option of ErrorClass.subclass().

BaseError.serialize(error)

error: ErrorInstance
Return value: ErrorObject

Converts error to an error plain object. All error properties are kept. Plugin options are also preserved.

BaseError.parse(errorObject)

errorObject: ErrorObject
Return value: ErrorInstance

Converts errorObject to an error instance. The original error classes are preserved providing they are subclasses of BaseError.

Options

Type: object

shallow

Type: boolean
Default: false

Unless this option is true, nested errors are also serialized/parsed. They can be inside other errors, plain objects or arrays.

const inner = new ExampleError('inner')
const error = new ExampleError('example', { props: { inner } })

BaseError.serialize(error).inner // { name: 'BaseError', message: 'inner', ... }
BaseError.serialize(error, { shallow: true }).inner // BaseError

const errorObject = BaseError.serialize(error)
BaseError.parse(errorObject).inner // BaseError
BaseError.parse(errorObject, { shallow: true }).inner // { name: '...', ... }

loose

Type: boolean
Default: false

By default, when the argument is not an Error instance or an error plain object, it is converted to one. If this option is true, it is kept as is instead.

BaseError.serialize('example') // { name: 'BaseError', message: 'example', ... }
BaseError.serialize('example', { loose: true }) // 'example'

BaseError.parse('example') // BaseError
BaseError.parse('example', { loose: true }) // 'example'

Configuration

Options can apply to (in priority order):

export const BaseError = ModernError.subclass('BaseError', {
  plugins: [modernErrorsSerialize],
  serialize: options,
})
export const ExampleError = BaseError.subclass('ExampleError', {
  serialize: options,
})
throw new ExampleError('...', { serialize: options })
BaseError.serialize(error, options)
BaseError.parse(errorObject, options)

Usage

JSON safety

Error plain objects are always safe to serialize with JSON.

const error = new ExampleError('message')
error.cycle = error

// Cycles make `JSON.stringify()` throw, so they are removed
console.log(BaseError.serialize(error).cycle) // undefined

Deep serialization/parsing

The loose option can be used to deeply serialize/parse objects and arrays.

const error = new ExampleError('message')
const deepArray = BaseError.serialize([{}, { error }], { loose: true })

const jsonString = JSON.stringify(deepArray)
const newDeepArray = JSON.parse(jsonString)

const newError = BaseError.parse(newDeepArray, { loose: true })[1].error
// ExampleError: message
//     at ...

Automatic serialization

error.toJSON() is defined. It is automatically called by JSON.stringify().

const error = new ExampleError('message')
const deepArray = [{}, { error }]

const jsonString = JSON.stringify(deepArray)
const newDeepArray = JSON.parse(jsonString)

const newError = BaseError.parse(newDeepArray, { loose: true })[1].error
// ExampleError: message
//     at ...

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 ExampleError('message')
const errorObject = BaseError.serialize(error)
const errorYamlString = dump(errorObject)
// name: ExampleError
// message: message
// stack: ExampleError: message ...
const newErrorObject = load(errorYamlString)
const newError = BaseError.parse(newErrorObject) // ExampleError: message

Additional error properties

const error = new ExampleError('message', { props: { prop: true } })
const errorObject = BaseError.serialize(error)
console.log(errorObject.prop) // true
const newError = BaseError.parse(errorObject)
console.log(newError.prop) // true

Aggregate errors

const error = new ExampleError('message', {
  errors: [new ExampleError('one'), new ExampleError('two')],
})

const errorObject = BaseError.serialize(error)
// {
//   name: 'ExampleError',
//   message: 'message',
//   stack: '...',
//   errors: [{ name: 'ExampleError', message: 'one', stack: '...' }, ...],
// }
const newError = BaseError.parse(errorObject)
// ExampleError: message
//   [errors]: [ExampleError: one, ExampleError: two]

Constructors

If an error with a custom class is parsed, its custom constructor is not called. However, any property previously set by that constructor is still preserved, providing it is serializable and enumerable.

const ExampleError = BaseError.subclass('ExampleError', {
  custom: class extends BaseError {
    constructor(message, options, prop) {
      super(message, options, prop)
      this.prop = prop
    }
  },
})

const error = new ExampleError('message', {}, true)
const errorObject = BaseError.serialize(error)
// `constructor(message, options, prop)` is not called
const newError = BaseError.parse(errorObject)
// But properties set by that `constructor(...)` are kept
console.log(newError.prop) // true

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!

modern-errors-serialize's People

Contributors

dependabot[bot] avatar ehmicky avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

modern-errors-serialize's Issues

Unable to compile in Typescript Node environment

Guidelines

  • Please search other issues to make sure this bug has not already been reported.
  • If this is related to a typo or the documentation being unclear, please click on the relevant page's Edit button (pencil icon) and suggest a correction instead.

Describe the bug

I am unable to import this library into my codebase. I think it is because the published version is not compiled to module system I can use (?).

It's quite possible there is something on my side that is causing the issue, or some configuration I could change to get it to work, but we already have > 80 other dependencies in our API that are not having any issues importing. (It's an express API)

Thanks in advance for any help, I'm quite excited to give this library a try!

Steps to reproduce

  1. Import and use the library
import ModernError from "modern-errors";

const BaseError = ModernError.subclass("BaseError");
throw new BaseError("test");
  1. Start app with ts-node-dev
  2. See following stack trace:
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/jack/workspace/my-project/api/node_modules/modern-errors/build/src/main.js from /Users/jack/workspace/my-project/api/src/index.ts not supported.
Instead change the require of main.js in /Users/jack/workspace/my-project/api/src/index.ts to a dynamic import() which is available in all CommonJS modules.
    at require.extensions..jsx.require.extensions..js (/private/var/folders/8n/dqgv9b4j797cqd34zb62ythw0000gn/T/ts-node-dev-hook-0371657800851346.js:114:20)
    at Object.nodeDevHook [as .js] (/Users/jack/workspace/my-project/api/node_modules/ts-node-dev/lib/hook.js:63:13)
    at Object.<anonymous> (/Users/jack/workspace/my-project/api/src/index.ts:68:41)
    at Module._compile (/Users/jack/workspace/my-project/api/node_modules/source-map-support/source-map-support.js:547:25)
    at Module.m._compile (/private/var/folders/8n/dqgv9b4j797cqd34zb62ythw0000gn/T/ts-node-dev-hook-0371657800851346.js:69:33)
    at require.extensions..jsx.require.extensions..js (/private/var/folders/8n/dqgv9b4j797cqd34zb62ythw0000gn/T/ts-node-dev-hook-0371657800851346.js:114:20)
    at require.extensions.<computed> (/private/var/folders/8n/dqgv9b4j797cqd34zb62ythw0000gn/T/ts-node-dev-hook-0371657800851346.js:71:20)
    at Object.nodeDevHook [as .ts] (/Users/jack/workspace/my-project/api/node_modules/ts-node-dev/lib/hook.js:63:13)
    at Object.<anonymous> (/Users/jack/workspace/my-project/api/node_modules/ts-node-dev/lib/wrap.js:104:1)
    at Module._compile (/Users/jack/workspace/my-project/api/node_modules/source-map-support/source-map-support.js:547:25)
    at Object.require.extensions..jsx.require.extensions..js (/private/var/folders/8n/dqgv9b4j797cqd34zb62ythw0000gn/T/ts-node-dev-hook-0371657800851346.js:95:24)

Configuration

tsconfig.json

{
  "compilerOptions": {
    "lib": ["es2021"],
    "target": "es2019",
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "strict": true,
    "rootDir": "./",
    "outDir": ".build",
    "allowJs": true,
    "sourceMap": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "typeRoots": ["node_modules/@types", "generated"],
  },
  "exclude": ["node_modules"]
}

Environment

 System:
   OS: macOS 13.0.1
   CPU: (10) arm64 Apple M1 Pro
   Memory: 158.23 MB / 16.00 GB
   Shell: 5.8.1 - /bin/zsh
 Binaries:
   Node: 16.14.0 - ~/.nvm/versions/node/v16.14.0/bin/node
   Yarn: 1.22.17 - /opt/homebrew/bin/yarn
   npm: 8.18.0 - ~/.nvm/versions/node/v16.14.0/bin/npm
 Browsers:
   Brave Browser: 100.1.37.113
   Chrome: 108.0.5359.124
   Firefox: 107.0.1
   Safari: 16.1

Pull request (optional)

  • I can submit a pull request.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.