JSON.parse(data) errors #1000
Description
It looks like the IPFS gateways return plain text errors, while the clients are expecting JSON, which is causing the json.parse to throw errors many times, (such as 404 not found
, method not allowed
etc.)
The problem is, while the json.parse
line 27 throws the error it discards the original data, leaving caller have no clue why the parse failed.
For example, here is one error received on the client side returned by IPFS deamon: if you put a breakpoint and observe the data, it has some valuable information such as: argument "key" is required
, which gets lost when the exception is thrown at line 27
The rethrown error at the call site contains stack with incorrect (and useless) error message:
"SyntaxError: Unexpected token a in JSON at position 0
at JSON.parse (<anonymous>)
at streamToValue (\node_modules\ipfs-http-client\src\utils\stream-to-json-value.js:25:18)
at concat (\node_modules\ipfs-http-client\src\utils\stream-to-value.js:12:22)
at ConcatStream.<anonymous> (\node_modules\concat-stream\index.js:32:43)
at ConcatStream.emit (events.js:187:15)
at finishMaybe (\node_modules\readable-stream\lib\_stream_writable.js:620:14)
at afterWrite (\node_modules\readable-stream\lib\_stream_writable.js:466:3)
at process._tickCallback (internal/process/next_tick.js:63:19)"
Suggestion:
- If clients are expecting JSON data, the gateways should return errors in JSON format, Else
- on the client side, e.g. at line 27, please include the original data received from the server in the error thrown so that callers get to know what the problem is, something like:
try {
res = JSON.parse(data)
} catch (err) {
return cb(new Error(data)) // <---- throw the data part of the error
}
or something like return cb(new Error("Invalid JSON: ${data}"))
For beginners, being able to understand the server errors is very important, since it is not always possible get things right the first time.