mixmaxhq/batchelor

JSON.parse SyntaxError when using GMAIL API

Closed this issue · 3 comments

Hi,

Great package btw

If invalid json is returned in the part.data.body then JSON.parse throws an error. It should be wrapped in a try catch. Example:

//  Parse response JSON
if (part.data.body) {
  try {
	  part.data.body = JSON.parse(part.data.body);
  } catch (e) {
	  console.error(e); 
  }
}

The error was happening when I was trying to label a old gmail message. It works most of the time. Google must be returning something strange in certain instances.

"err": {
        "message": "Unexpected token N in JSON at position 0",
        "name": "SyntaxError",
        "stack": "SyntaxError: Unexpected token N in JSON at position 0\n    at JSON.parse (<anonymous>)\n    at PartStream.<anonymous> (/src/node_modules/batchelor/lib/batchelor.js:223:33)\n    at emitNone (events.js:91:20)\n    at PartStream.emit (events.js:186:7)\n    at endReadableNT (_stream_readable.js:974:12)\n    at _combinedTickCallback (internal/process/next_tick.js:74:11)\n    at process._tickDomainCallback (internal/process/next_tick.js:122:9)"
    }

To replicate yourself, change the following on line 223

JSON.parse('make this bad json' + part.data.body);

Hope you able to fix. I can raise a PR if needed, but felt the change was simple enough to be done by established committers.

Regards

Dan

Sorry for the delay @dperry, was this not an issue purely because you were trying to parse JSON data that was already JSON data?

For me, the extra parsing is happening in the lib, not my code

looks like it was never a double parsing issue. The issue is that the response is a string whenever a 401 is returned. The 401 was because I was using an old access token. The solution is to get the access token from the oauth client because it will internally use a refresh token to provide a valid access token. Everything is working like a charm for me.