Skip to content

Android: fetch throws Java exception on malformed JSON response #9178

@overminder

Description

@overminder

Context

  • Reproducible on react-native@{0.29.0,0.30.0,0.31.0-rc.1,0.34.1,0.35.0-rc.0}
  • Android 4.4, 5.0, 5.1 and 6.0 (shouldn't matter)

Stack Trace

E/unknown:React: Exception in native call from JS
  com.facebook.react.devsupport.JSException: Failed to create String from JSON
    at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
    ...
  Caused by: com.facebook.jni.CppException: Failed to create String from JSON

Reproduction

  1. Create a fresh react-native project by react-native init SomeProject.
  2. Edit SomeProject/index.android.js by adding a fetch(kUri).then(x => x.json()); statement in SomeProject component class's componentDidMount method, where kUri points to a file served by a HTTP server. The content of the file is:
$ hexdump some-binary
0000000 ed b7 a1 0a
0000004

or in base64:

$ base64 some-binary
7behCg==

The HTTP response header for the URI is:

HTTP/1.1 200 OK
Content-Type: text/plain
Connection: close

Then run react-native run-android and observe a red screen that says Failed to create String from JSON (this is on 0.31.0-rc.1, the exact error message might differ in different react-native versions).

What's Expected

Parsing malformed JSON response bodies should just raise JS exceptions but not native exceptions - we have no way to catch the latter from JS.

Analysis

A quick search suggests that this error can only be thrown from Value::fromJSON:

:~/react-native/ReactAndroid (0.31-stable)
$ ag 'Failed to create'
src/main/jni/react/Value.cpp
41:    throwJSExecutionException("Failed to create String from JSON");

What it does is just calling JSValueMakeFromJSONString which can return NULL on invalid inputs (Apple's doc).

See Also

#9117

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions