Permalink
Browse files

Better error message when trying to parse a empty body in fetch

Summary: Previously, trying to parse an empty network body would throw "Unexpected EOF" from JSON.parse. Now we explicitly call out the error and provide steps for possible mitigation.

Reviewed By: frantic

Differential Revision: D3528297

fbshipit-source-id: 3b52c9491c1504c282eb9bc12ed46069cb6cbd60
  • Loading branch information...
1 parent b5c3550 commit eeb9cd8075886722df84e91ab64f9513f41cd0fa @astreet astreet committed with Facebook Github Bot Jul 7, 2016
Showing with 22 additions and 1 deletion.
  1. +22 −1 Libraries/Fetch/fetch.js
@@ -11,6 +11,8 @@
*
* @providesModule fetch
* @nolint
+ *
+ * NOTE: This file has local changes for RN and is not a straight copy!
*/
/* eslint-disable */
'use strict';
@@ -240,7 +242,26 @@ var self = {};
}
this.json = function() {
- return this.text().then(JSON.parse)
+ var status = this.status;
+ return this.text().then(function(text) {
+ if (!text) {
+ var errorText =
+ 'Trying to parse the body of a network response as JSON, but the ' +
+ 'body is null or empty.';
+ if (status !== 200) {
+ errorText +=
+ '\n\nThis can be the result of not properly checking for a 200 OK ' +
+ 'status code before trying to parse the body (the status code for ' +
+ 'this response was ' + status + ').';
+ } else {
+ errorText +=
+ '\n\nThe status code for this response was 200 OK, so nothing ' +
+ 'went obviously wrong. Is your server configured properly?';
+ }
+ throw new Error(errorText);
+ }
+ return JSON.parse(text);
+ });
}
return this

0 comments on commit eeb9cd8

Please sign in to comment.