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

JSON.parse(data) errors #1000

Closed
Closed
@KrishnaPG

Description

@KrishnaPG

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

image

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:

  1. If clients are expecting JSON data, the gateways should return errors in JSON format, Else
  2. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions