Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug] Error is not stringified #77

Open
ghengeveld opened this issue Nov 12, 2021 · 0 comments
Open

[Bug] Error is not stringified #77

ghengeveld opened this issue Nov 12, 2021 · 0 comments
Labels
bug Something isn't working

Comments

@ghengeveld
Copy link
Member

ghengeveld commented Nov 12, 2021

Describe the bug

Stringifying an Error instance will yield "{}".

Steps to reproduce the behavior

import { stringify, parse } from "telejson";

const error = new Error("Oops");

const string = stringify(error);
console.log({ string }); // => { string: "{}" }

const parsed = parse(string);
console.log(parsed); // => {}

https://codesandbox.io/s/delicate-fire-dto12?file=/src/index.js

Expected behavior

A stringified Error should look like:

{ "name": "CustomError", "message": "Oops", "stack": "CustomError: Oops\n    at <anonymous>:1:1" }

Parsing this should yield an Error instance with these properties restored.

const { name, message, stack } = JSON.parse(string); // or something safer
const error = new Error(message);
Object.defineProperty(error, 'name', { value: name });
Object.defineProperty(error, 'stack', { value: stack });

This doesn't yield the original CustomError class instance, but I suppose it's better to not attempt to restore that since it may have other custom properties or methods which we won't be able to restore anyway.

Workaround

const error = new Error("Oops");
const { name, message, stack } = error;
const e = { name, message, stack };

However this doesn't yield an Error instance, just a plain object.

@ghengeveld ghengeveld added the bug Something isn't working label Nov 12, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant