Serialize/deserialize an error into a plain object
Installations
npm install serialize-error
Developer Guide
Typescript
Yes
Module System
ESM
Min. Node Version
>=14.16
Node Version
18.18.2
NPM Version
9.2.0
Score
99.4
Supply Chain
99.5
Quality
75.9
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Unable to fetch Contributors
Languages
JavaScript (97.74%)
TypeScript (2.26%)
Developer
sindresorhus
Download Statistics
Total Downloads
1,216,371,891
Last Day
316,192
Last Week
7,550,629
Last Month
31,236,814
Last Year
350,135,884
GitHub Statistics
544 Stars
76 Commits
63 Forks
10 Watching
1 Branches
22 Contributors
Sponsor this package
Package Meta Information
Latest Version
11.0.3
Package Id
serialize-error@11.0.3
Unpacked Size
16.34 kB
Size
5.08 kB
File Count
7
NPM Version
9.2.0
Node Version
18.18.2
Publised On
10 Nov 2023
Total Downloads
Cumulative downloads
Total Downloads
1,216,371,891
Last day
-11.7%
316,192
Compared to previous day
Last week
-2.5%
7,550,629
Compared to previous week
Last month
-7.1%
31,236,814
Compared to previous month
Last year
11.6%
350,135,884
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
serialize-error
Serialize/deserialize an error into a plain object
Useful if you for example need to JSON.stringify()
or process.send()
the error.
Install
1npm install serialize-error
Usage
1import {serializeError, deserializeError} from 'serialize-error'; 2 3const error = new Error('🦄'); 4 5console.log(error); 6//=> [Error: 🦄] 7 8const serialized = serializeError(error); 9 10console.log(serialized); 11//=> {name: 'Error', message: '🦄', stack: 'Error: 🦄\n at Object.<anonymous> …'} 12 13const deserialized = deserializeError(serialized); 14 15console.log(deserialized); 16//=> [Error: 🦄]
Error constructors
When a serialized error with a known name
is encountered, it will be deserialized using the corresponding error constructor, while unknown error names will be deserialized as regular errors:
1import {deserializeError} from 'serialize-error'; 2 3const known = deserializeError({ 4 name: 'TypeError', 5 message: '🦄' 6}); 7 8console.log(known); 9//=> [TypeError: 🦄] <-- Still a TypeError 10 11const unknown = deserializeError({ 12 name: 'TooManyCooksError', 13 message: '🦄' 14}); 15 16console.log(unknown); 17//=> [Error: 🦄] <-- Just a regular Error
The list of known errors can be extended globally. This also works if serialize-error
is a sub-dependency that's not used directly.
1import {errorConstructors} from 'serialize-error'; 2import {MyCustomError} from './errors.js' 3 4errorConstructors.set('MyCustomError', MyCustomError)
Warning: Only simple and standard error constructors are supported, like new MyCustomError(message)
. If your error constructor requires a second parameter or does not accept a string as first parameter, adding it to this map will break the deserialization.
API
serializeError(value, options?)
Serialize an Error
object into a plain object.
- Non-error values are passed through.
- Custom properties are preserved.
- Non-enumerable properties are kept non-enumerable (name, message, stack).
- Enumerable properties are kept enumerable (all properties besides the non-enumerable ones).
- Buffer properties are replaced with
[object Buffer]
. - Circular references are handled.
- If the input object has a
.toJSON()
method, then it's called instead of serializing the object's properties. - It's up to
.toJSON()
implementation to handle circular references and enumerability of the properties.
value
Type: Error | unknown
toJSON implementation examples
1import {serializeError} from 'serialize-error'; 2 3class ErrorWithDate extends Error { 4 constructor() { 5 super(); 6 this.date = new Date(); 7 } 8} 9 10const error = new ErrorWithDate(); 11 12serializeError(error); 13// => {date: '1970-01-01T00:00:00.000Z', name, message, stack}
1import {serializeError} from 'serialize-error'; 2 3const error = new Error('Unicorn'); 4 5error.horn = { 6 toJSON() { 7 return 'x'; 8 } 9}; 10 11serializeError(error); 12// => {horn: 'x', name, message, stack}
deserializeError(value, options?)
Deserialize a plain object or any value into an Error
object.
Error
objects are passed through.- Objects that have at least a
message
property are interpreted as errors. - All other values are wrapped in a
NonError
error. - Custom properties are preserved.
- Non-enumerable properties are kept non-enumerable (name, message, stack, cause).
- Enumerable properties are kept enumerable (all properties besides the non-enumerable ones).
- Circular references are handled.
- Native error constructors are preserved (TypeError, DOMException, etc) and more can be added.
value
Type: {message: string} | unknown
options
Type: object
maxDepth
Type: number
Default: Number.POSITIVE_INFINITY
The maximum depth of properties to preserve when serializing/deserializing.
1import {serializeError} from 'serialize-error'; 2 3const error = new Error('🦄'); 4error.one = {two: {three: {}}}; 5 6console.log(serializeError(error, {maxDepth: 1})); 7//=> {name: 'Error', message: '🦄', one: {}} 8 9console.log(serializeError(error, {maxDepth: 2})); 10//=> {name: 'Error', message: '🦄', one: { two: {}}}
useToJSON
Type: boolean
Default: true
Indicate whether to use a .toJSON()
method if encountered in the object. This is useful when a custom error implements its own serialization logic via .toJSON()
but you prefer to not use it.
isErrorLike(value)
Predicate to determine whether a value looks like an error, even if it's not an instance of Error
. It must have at least the name
, message
, and stack
properties.
1import {isErrorLike} from 'serialize-error'; 2 3const error = new Error('🦄'); 4error.one = {two: {three: {}}}; 5 6isErrorLike({ 7 name: 'DOMException', 8 message: 'It happened', 9 stack: 'at foo (index.js:2:9)', 10}); 11//=> true 12 13isErrorLike(new Error('🦄')); 14//=> true 15 16isErrorLike(serializeError(new Error('🦄')); 17//=> true 18 19isErrorLike({ 20 name: 'Bluberricious pancakes', 21 stack: 12, 22 ingredients: 'Blueberry', 23}); 24//=> false
No vulnerabilities found.
Reason
security policy file detected
Details
- Info: security policy file detected: .github/security.md:1
- Info: Found linked content: .github/security.md:1
- Info: Found disclosure, vulnerability, and/or timelines in security policy: .github/security.md:1
- Info: Found text in security policy: .github/security.md:1
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
- Info: project has a license file: license:0
- Info: FSF or OSI recognized license: MIT License: license:0
Reason
0 existing vulnerabilities detected
Reason
Found 11/30 approved changesets -- score normalized to 3
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/main.yml:1
- Info: no jobLevel write permissions found
Reason
0 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/serialize-error/main.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/sindresorhus/serialize-error/main.yml/main?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/main.yml:21
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'main'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 11 are checked with a SAST tool
Score
4.3
/10
Last Scanned on 2024-12-16
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to serialize-error
@types/serialize-error
Stub TypeScript definitions entry for serialize-error, which provides its own types definitions
serialize-error-cjs
> Serialize/deserialize an error into a plain object in commonjs
@dotcom-reliability-kit/serialize-error
A utility function to serialize an error object in a way that's friendly to loggers, view engines, and converting to JSON
@tapjs/node-serialize
Stream TAP test data as a serialized node:test stream