Skip to content

Commit 92c530d

Browse files
[fix] Properly handle JSON.stringify errors (#84)
JSON.stringify method throws when passed a circular object.
1 parent dc4f475 commit 92c530d

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

index.js

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,8 @@ exports.Decoder = Decoder;
113113

114114
function Encoder() {}
115115

116+
var ERROR_PACKET = exports.ERROR + '"encode error"';
117+
116118
/**
117119
* Encode a packet as a single string if non-binary, or as a
118120
* buffer sequence, depending on packet type.
@@ -128,8 +130,7 @@ Encoder.prototype.encode = function(obj, callback){
128130

129131
if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
130132
encodeAsBinary(obj, callback);
131-
}
132-
else {
133+
} else {
133134
var encoding = encodeAsString(obj);
134135
callback([encoding]);
135136
}
@@ -166,13 +167,26 @@ function encodeAsString(obj) {
166167

167168
// json data
168169
if (null != obj.data) {
169-
str += JSON.stringify(obj.data);
170+
var payload = tryStringify(obj.data);
171+
if (payload !== false) {
172+
str += payload;
173+
} else {
174+
return ERROR_PACKET;
175+
}
170176
}
171177

172178
debug('encoded %j as %s', obj, str);
173179
return str;
174180
}
175181

182+
function tryStringify(str) {
183+
try {
184+
return JSON.stringify(str);
185+
} catch(e){
186+
return false;
187+
}
188+
}
189+
176190
/**
177191
* Encode packet as 'buffer sequence' by removing blobs, and
178192
* deconstructing packet into object with placeholders and

test/parser.js

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
var parser = require('../index.js');
22
var expect = require('expect.js');
33
var helpers = require('./helpers.js');
4-
var encode = parser.encode;
5-
var decode = parser.decode;
64

75
describe('parser', function(){
86

@@ -61,6 +59,24 @@ describe('parser', function(){
6159
});
6260
});
6361

62+
it('properly handles circular objects', function() {
63+
var a = {};
64+
a.b = a;
65+
66+
var data = {
67+
type: parser.EVENT,
68+
data: a,
69+
id: 1,
70+
nsp: '/'
71+
}
72+
73+
var encoder = new parser.Encoder();
74+
75+
encoder.encode(data, function(encodedPackets) {
76+
expect(encodedPackets[0]).to.be('4"encode error"');
77+
});
78+
});
79+
6480
it('decodes a bad binary packet', function(){
6581
try {
6682
var decoder = new parser.Decoder();

0 commit comments

Comments
 (0)