diff --git a/src/utils/send-request.js b/src/utils/send-request.js index 219327adf..b9f850561 100644 --- a/src/utils/send-request.js +++ b/src/utils/send-request.js @@ -13,9 +13,27 @@ const log = require('debug')('ipfs-http-client:request') // -- Internal +function hasJSONHeaders (res) { + return res.headers['content-type'] && + res.headers['content-type'].indexOf('application/json') === 0 +} + function parseError (res, cb) { const error = new Error(`Server responded with ${res.statusCode}`) + if (!hasJSONHeaders(res)) { + return streamToValue(res, (err, data) => { + // the `err` here refers to errors in stream processing, which + // we ignore here, since we already have a valid `error` response + // from the server above that we have to report to the caller. + if (data && data.length) { + error.message = data.toString() + } + error.code = res.statusCode + cb(error) + }) + } + streamToJsonValue(res, (err, payload) => { if (err) { return cb(err) @@ -34,8 +52,7 @@ function onRes (buffer, cb) { return (res) => { const stream = Boolean(res.headers['x-stream-output']) const chunkedObjects = Boolean(res.headers['x-chunked-output']) - const isJson = res.headers['content-type'] && - res.headers['content-type'].indexOf('application/json') === 0 + const isJson = hasJSONHeaders(res) if (res.req) { log(res.req.method, `${res.req.getHeaders().host}${res.req.path}`, res.statusCode, res.statusMessage) diff --git a/src/utils/stream-to-json-value.js b/src/utils/stream-to-json-value.js index e42de2fc6..2ae83e50d 100644 --- a/src/utils/stream-to-json-value.js +++ b/src/utils/stream-to-json-value.js @@ -24,7 +24,7 @@ function streamToJsonValue (res, cb) { try { res = JSON.parse(data) } catch (err) { - return cb(err) + return cb(new Error(`Invalid JSON: ${data}`)) } cb(null, res)