From e8344e36bb921eb766db78899d3e44044e4f9d91 Mon Sep 17 00:00:00 2001 From: Mike Gerwitz Date: Thu, 28 May 2015 09:42:00 -0400 Subject: [PATCH] dapi.format.JsonResponse response text output value on parse failure --- src/dapi/format/JsonResponse.js | 12 ++++++++--- test/dapi/format/JsonResponseTest.js | 32 +++++++++++++++++++++------- 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/src/dapi/format/JsonResponse.js b/src/dapi/format/JsonResponse.js index db357e8..d0f08fe 100644 --- a/src/dapi/format/JsonResponse.js +++ b/src/dapi/format/JsonResponse.js @@ -33,7 +33,10 @@ module.exports = Trait( 'JsonResponse' ) /** * Processes response as JSON * - * Will return an error if the response is not valid JSON. + * If the response is not valid JSON, an error will be returned. The + * output value will be an object with a single + * property---`text`---containing the response text that failed to + * parse. * * @param {string} data binary data to transmit * @param {function(?Error,*)} callback continuation upon reply @@ -56,8 +59,11 @@ module.exports = Trait( 'JsonResponse' ) } catch ( e ) { - // parsing failed - callback( e, null ); + // parsing failed; provide response text in addition to + // original data so that the caller can handle how they + // please + callback( e, { text: resp } ); + return; } diff --git a/test/dapi/format/JsonResponseTest.js b/test/dapi/format/JsonResponseTest.js index 2932a56..9211105 100644 --- a/test/dapi/format/JsonResponseTest.js +++ b/test/dapi/format/JsonResponseTest.js @@ -55,15 +55,31 @@ describe( 'dapi.format.JsonRepsonse trait', function() } ); - it( 'returns error if JSON parsing fails', function( done ) + describe( 'when JSON parsing fails', function() { - _createStubbedDapi( null, 'ERR' ) - .request( '', function( err, data ) - { - expect( err ).to.be.instanceOf( Error ); - expect( data ).to.equal( null ); - done(); - } ); + it( 'returns error', function( done ) + { + _createStubbedDapi( null, 'ERR' ) + .request( '', function( err, data ) + { + expect( err ).to.be.instanceOf( Error ); + done(); + } ); + } ); + + + it( 'provides bad text as object.text', function( done ) + { + var text = 'NOT JSON'; + + _createStubbedDapi( null, text ) + .request( '', function( err, data ) + { + expect( data ).to.be.a( 'object' ); + expect( data.text ).to.equal( text ); + done(); + } ); + } ); } );