Skip to content
This repository has been archived by the owner on Mar 10, 2020. It is now read-only.

JSON.parse error reporting: with invalid json: in the error string #1001

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions src/utils/send-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/utils/stream-to-json-value.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down