Skip to content

Commit 9d9d931

Browse files
committed
Handle circular object structures in Errors correctly. (detect and ignore them)
1 parent 837fcf7 commit 9d9d931

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

lib/util/getSerializableError.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,15 @@
22
module.exports = function getSerializableError(err) {
33
//this copying of properties is needed to get Error properties serialized by JSON.stringify
44
var output = {};
5-
Object.getOwnPropertyNames(err).forEach(function (i) {
6-
if (err[i] && i !== "arguments") {
7-
output[i] = err[i];
5+
Object.getOwnPropertyNames(err).forEach(function (property) {
6+
if (err[property]) {
7+
try{
8+
//only add properties that can be stringified
9+
JSON.stringify(err[property]);
10+
output[property] = err[property];
11+
} catch (ex){
12+
13+
}
814
}
915
});
1016
return output;

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
{
22
"author":"Allan Ebdrup",
33
"name":"nodeerrors",
4-
"version":"1.0.3",
4+
"description": "error handling module for node",
5+
"version":"1.0.4",
56
"repository":{
67
"type":"git",
78
"url":"https://github.com/Muscula/nodeerrors"

test/unit/getSerializableError.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,16 @@ describe("when passed an error", function () {
1515
expect(serialized.stack).to.be.ok;
1616
expect(error).to.eql(serialized);
1717
});
18+
it('will make only copy properties that can be JSON.serialized', function () {
19+
var getSerialiazableError = require("../../lib/util/getSerializableError");
20+
var sourceError = new Error("This is my error");
21+
//create circular reference
22+
var o= { circle : {}};
23+
o.circle = o;
24+
sourceError.test = o;
25+
var error = getSerialiazableError(sourceError);
26+
var serialized = JSON.parse(JSON.stringify(error));
27+
expect(serialized.stack).to.be.ok;
28+
expect(error).to.eql(serialized);
29+
});
1830
});

0 commit comments

Comments
 (0)