serialize-error-cjs
v0.1.3
Published
> Serialize/deserialize an error into a plain object in commonjs
Downloads
339,995
Maintainers
Readme
serialize-error-cjs
Serialize/deserialize an error into a plain object in commonjs
Loosely based on serialize-error, but with support for commonjs projects.
Useful if you for example need to JSON.stringify()
or process.send()
the error.
Install
npm install serialize-error-cjs
Usage
import {serializeError, deserializeError} from 'serialize-error-cjs';
const error = new Error('🦄');
console.log(error);
//=> [Error: 🦄]
const serialized = serializeError(error);
console.log(serialized);
//=> {name: 'Error', message: '🦄', stack: 'Error: 🦄\n at Object.<anonymous> …'}
const deserialized = deserializeError(serialized);
console.log(deserialized);
//=> [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:
import {deserializeError} from 'serialize-error';
const known = deserializeError({
name: 'TypeError',
message: '🦄'
});
console.log(known);
//=> [TypeError: 🦄] <-- Still a TypeError
const unknown = deserializeError({
name: 'TooManyCooksError',
message: '🦄'
});
console.log(unknown);
//=> [Error: 🦄] <-- Just a regular Error
The list of known errors can be extended globally. This also works if serialize-error-cjs
is a sub-dependency that's not used directly.
import {errorConstructors} from 'serialize-error-cjs';
import {MyCustomError} from './errors.js'
errorConstructors.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)
Serialize an Error
object into a plain object.
- Custom properties NOT are preserved.
- Non-enumerable properties are kept non-enumerable (name, message, stack).
- Circular references are NOT handled.
value
Type: Error
deserializeError(value)
Deserialize a plain object or any value into an Error
object.
- All passed values are interpreted as errors
- Custom properties are NOT preserved
- Non-enumerable properties are kept non-enumerable (name, message, stack, cause)
- Circular references are NOT handled
value
Type: {message: string} | unknown