jpillora / node-edit-google-spreadsheet

A simple API for editing Google Spreadsheets
304 stars 101 forks source link

On sheetReady with incorrect spreadsheetId returns non-json string #27

Closed christiaanwesterbeek closed 10 years ago

christiaanwesterbeek commented 10 years ago

When you try to load a sheet with a incorrect spreadsheetId, like shown underneath, the callback is called with a weird err argument

var Spreadsheet = require('edit-google-spreadsheet');
Spreadsheet.load({
    spreadsheetId: '1234565464',
    worksheetName: 'Sheet1',
    username: 'my-name@google.email.com',
    password: 'my-5uper-t0p-secret-password'
  }, function sheetReady(err, spreadsheet) {
    if (err)  
      console.log('err', err)
});

This is output in the console

Failed to parse JSON response: 'SyntaxError: Unexpected token T':
The spreadsheet at this URL cannot be found...

When I debug lib/index.js line 93, I see that the body of the response is plain text and no JSON, so it should not be parsed.

The spreadsheet at this URL cannot be found...

BTW: the status of the response is not 200 but 400 in this case (because it's a wrong spreadsheetId that cannot be found) and. We can use that to change a few lines in lib/index.js to handle the non-json result on error.

try {
  result = JSON.parse(body);
} catch(err) {
  return callback("Failed to parse JSON response: '"+err+"':\n"+body, null);
}

should become:

try {
  result = JSON.parse(body);
} catch(err) {
  if (response.status!= 200)
    return callback(body);
  else  
    return callback("Failed to parse JSON response: '"+err+"':\n"+body, null);
}

I guess that the current url spreadsheets.google.com/feeds/ used in this module (line 86 in lib/index.js) returns plain strings as errors that are non-json by default. However I can't find the documentation to back that up.