Skip to content

Commit

Permalink
Catch exception and report it when making a network request with inva…
Browse files Browse the repository at this point in the history
…lid URL on Android

Currently if you invoke `fetch()` with an invalid URL ("aaa" for
example) you cannot catch the error in javascript since it's not
reported. Instead the entire app crashes.

Fixes facebook#7436 and facebook#18087

Hopefully.
  • Loading branch information
jcurtis committed Feb 26, 2018
1 parent 2ef9b7f commit d475bae
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,13 @@ public void sendRequest(
return;
}

Request.Builder requestBuilder = new Request.Builder().url(url);
Request.Builder requestBuilder;
try {
requestBuilder = new Request.Builder().url(url);
} catch (Exception e) {
ResponseUtil.onRequestError(eventEmitter, requestId, e.getMessage(), null);
return;
}

if (requestId != 0) {
requestBuilder.tag(requestId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,34 @@ public void testFailPostWithoutContentType() throws Exception {
verifyErrorEmit(emitter, 0);
}

@Test
public void testFailInvalidUrl() throws Exception {
RCTDeviceEventEmitter emitter = mock(RCTDeviceEventEmitter.class);
ReactApplicationContext context = mock(ReactApplicationContext.class);
when(context.getJSModule(any(Class.class))).thenReturn(emitter);

OkHttpClient httpClient = mock(OkHttpClient.class);
OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class);
when(clientBuilder.build()).thenReturn(httpClient);
when(httpClient.newBuilder()).thenReturn(clientBuilder);
NetworkingModule networkingModule = new NetworkingModule(context, "", httpClient);

mockEvents();

networkingModule.sendRequest(
"GET",
"aaa",
/* requestId */ 0,
/* headers */ JavaOnlyArray.of(),
/* body */ null,
/* responseType */ "text",
/* useIncrementalUpdates*/ true,
/* timeout */ 0,
/* withCredentials */ false);

verifyErrorEmit(emitter, 0);
}

private static void verifyErrorEmit(RCTDeviceEventEmitter emitter, int requestId) {
ArgumentCaptor<WritableArray> captor = ArgumentCaptor.forClass(WritableArray.class);
verify(emitter).emit(eq("didCompleteNetworkResponse"), captor.capture());
Expand Down Expand Up @@ -630,4 +658,4 @@ public Object answer(InvocationOnMock invocation) throws Throwable {
assertThat(requestIdArguments.getAllValues().contains(idx + 1)).isTrue();
}
}
}
}

0 comments on commit d475bae

Please sign in to comment.