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

Consider Object.toJSON() method #20

Closed
samchon opened this issue May 7, 2019 · 3 comments · Fixed by #38
Closed

Consider Object.toJSON() method #20

samchon opened this issue May 7, 2019 · 3 comments · Fixed by #38

Comments

@samchon
Copy link

samchon commented May 7, 2019

Some program defines custom error type (e.g. MyError) and the custom error type also may have the toJSON() method, that would be used in JSON.stringify(). In such reason, I recommend serializeError function to inspects the toJSON() method first.

class MyError extends Error
{
    public readonly code: number;
    public readonly type: string;
    
    public constructor(code: number, type: string, message: string);
    public toJSON(): object
    {
        return {
            name: this.name, stack: this.stack, message: this.message,
            code: this.code, type: this.type
        };
    }
}
@sindresorhus
Copy link
Owner

Makes sense. PR welcome.

@sindresorhus sindresorhus changed the title Consider Object.toJSON() method. Consider Object.toJSON() method May 7, 2019
@moltar
Copy link

moltar commented Oct 26, 2019

On the other hand, I am using serializeError to implement toJSON method:

  public toJSON() {
    return serializeError(this)
  }

So this would be a breaking change.

@sindresorhus
Copy link
Owner

We could use a Symbol to prevent self-recursive serialization.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants