mattinsler/longjohn

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

Closed this issue · 7 comments

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?

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

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

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.

Makes sense, thx

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
});

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.

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