From eeb9cd8075886722df84e91ab64f9513f41cd0fa Mon Sep 17 00:00:00 2001 From: Andy Street Date: Thu, 7 Jul 2016 11:03:09 -0700 Subject: [PATCH] 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 --- Libraries/Fetch/fetch.js | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/Libraries/Fetch/fetch.js b/Libraries/Fetch/fetch.js index 7cb122a07..171030496 100644 --- a/Libraries/Fetch/fetch.js +++ b/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