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

res.json(err) causes "Converting circular structure to JSON" #22

Closed
binarykitchen opened this issue Oct 28, 2013 · 7 comments
Closed

res.json(err) causes "Converting circular structure to JSON" #22

binarykitchen opened this issue Oct 28, 2013 · 7 comments

Comments

@binarykitchen
Copy link

In my app I am json-sending errors to the client for some development environments so that these become visible on the browser.

I understand that longjohn is adding circular stuff to the default error instances. And so, Express' res.json cannot deal with these error instances anymore.

So, do you have any tricks or an advice for that?

@mattinsler
Copy link
Owner

You can use https://npmjs.org/package/json-stringify-safe to stringify the error and pass that into res.json.

@binarykitchen
Copy link
Author

Mmmmhhh, thanks for that. Why is Express not using it then?

@mattinsler
Copy link
Owner

It would add some overhead to every single response that uses res.json, which express can't assume a user would be willing to take on. It just doesn't make sense for the framework to make those types of choices for users.

@binarykitchen
Copy link
Author

Makes sense, thx

@binarykitchen
Copy link
Author

I found a better way without adding much overhead nor an external module. I modified the toJSON method like that:

Object.defineProperty(Error.prototype, 'toJSON', {
    value: function() {
        var json = {};

        Object.getOwnPropertyNames(this).forEach(function(key) {
            // ignore long john stuff like '__cached_trace__'
            if (!/__(.)+__/.test(key)) {
                json[key] = this[key];
            }
        }, this);

        return json;
    },
    configurable: true
});

@mattinsler
Copy link
Owner

This definitely works. Be careful when augmenting the core prototypes. You're better off usually adding a method, like toCleanJSON or something like that so that the core type still operates as expected by any other code that may utilize it.

@binarykitchen
Copy link
Author

@mattinsler Agree with you. I just changed that into toCleanJSON in my code.

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

No branches or pull requests

2 participants