[Android] Maybe fetch errors can be a little more descriptive?
Using RN Version: 0.24.1
I ran into an issue that ended up eating quite a bit of my time (because I'm dumb). I figured out the solution, but I wanted to share what happened, because maybe RN can ease debugging pain by being a little bit more descriptive about what's causing fetch/xhr errors.
I'm building something that uploads images to an API. Here's the code that I was having problems with:
export const uploadImage = (api, auth, imageUri) => {
const url = `${api.url}${PATH_IMAGES}`;
const headers = new Headers();
headers.append('Client-Id', api.clientId);
headers.append('Authorization', `Bearer ${auth.access_token}`);
const body = new FormData();
body.append('image', {
uri: imageUri,
name: `${new Date().getTime()}.jpg`,
});
const fetchData = {
method: 'POST',
headers,
body
};
return fetch(url, fetchData)
.then(handleErrors)
.then(handleJson);
};
This works on iOS, but it doesn't work on Android. On Android, this doesn't even get to make an HTTP Request, I get an error saying TypeError: Network Request Failed.
That's doesn't give me a lot of information, so I did some debugging and put a breakpoint on fetch.js to figure out the actual problem. Looking at the xhr object we see the issue: Binary FormData part needs a content-type header

Googling that string takes you to this line in NetworkingModule.java: https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/modules/network/NetworkingModule.java#L417
That error message is a little confusing. Do I need to add content-type: 'multipart/form-data' to my request headers? I did and that didn't fix anything, so I didn't understand what was going on.
Ultimately I did find my solution. I was missing something when creating the FormData: I needed a type field with the mimetype of the image. The correct(ish) code is:
const body = new FormData();
body.append('image', {
uri: imageUri,
type: 'image/jpeg',
name: `${new Date().getTime()}.jpg`,
});
So there seem to be two issues:
- I didn't get the root cause of the error in the Chrome debug console, because it's not surfaced up from Java to js.
- I wasn't missing a "content-type header" like the error mentioned, what I was missing was the mime-type of my image in the FormData.
So, fetch and xhr are polyfills with an underlying Java implementation. The underlying Java code adds another layer of complexity and potential source of exceptions. Given that, I think it's important for us to be able to see those underlying exceptions (at least the message string) in the chrome console so we can more easily debug.
I did a lot of googling on the bug I was having and I didn't find much, so this could just be one of those things that happens to me and no one else in the world, but I felt it was important to share.
Thanks for all the research you've done on this. I'm glad you found the solution but I think you're right, there definitely seems like there are things that perhaps could be done here to make things better.
@mkonicek @kmagiera any thoughts on this?
I think this is actually the right behavior - the fetch api doesn't return a rejected promise when there's an error, unless it's a network error, and this is not a network error. https://www.tjvantoll.com/2015/09/13/fetch-and-errors/ When you are using fetch you are supposed to inspect the resulting object to see what went wrong. It's kinda weird (ie its not like jquery) but that is what fetch is supposed to do. So, I'm going to close this issue but if you have a specific suggestion for how this failure case should have more clear communication without violating how fetch is supposed to work feel free to open another issue.
Hi,
If I may add a few details as I have been struggling myself for a while before getting a clear understanding of the problem.
I believe that @dslounge's issue actually was a "real" network error, triggering the xhr.onerror callback from fetch thus the 'Network Request Failed' message, as it is shown by the hasError: true property of the xhr object.
So, in this case, the promise is indeed rejected and there is no response to introspect to get the status code because the server throws an exception instead of sending any HTTP response.
Could this be improved on the fetch polyfill side? As it is well described in https://github.com/github/fetch/issues/367#issuecomment-255894493, there is no consistent way for fetch to provide more information.
But, taking a closer look at the XMLHttpRequest React Native implementation, we can see that it allows setting an interceptor with a loadingFailed function as an error callback, which has the actual error as an argument: https://github.com/facebook/react-native/blob/master/Libraries/Network/XMLHttpRequest.js#L380.
For instance you can do:
class NetworkInterceptor {
loadingFailed(id: number, error: string) {
handleNetworkError(new Error(`Network request failed: ${error}`));
}
requestSent() {
}
responseReceived() {
}
dataReceived() {
}
loadingFinished() {
}
}
const handleNetworkError = (error) => {
// handle error here
};
XMLHttpRequest.setInterceptor(new NetworkInterceptor());
This is actually used by https://github.com/facebook/react-native/blob/master/Libraries/JSInspector/NetworkAgent.js
Hope this helps!
@ataillefer you sir, just saved me a ton of hours in debugging. :P. Found my issue on android.
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
Now onto the next error... sigh...
Thanks!
Hi guys!
I'm solving this problem in the server. Following this https://www.bjornjohansen.no/securing-nginx-ssl
Precisely this part:
Intermediate Certificate Advisory
The certificate issuer will most likely provide you with a Intermediate Certificate Advisory or two. You MUST install the intermediate certificates on the server together with the certificate.
Save the intermediate certificate to /etc/ssl/certs/
In my case the two provided intermediate certs will be these two files:
COMODORSAAddTrustCA.crt COMODORSADomainValidationSecureServerCA.crt
Concatenate the certificates to one file (order is important):
$ cat /etc/ssl/certs/example.com.crt /etc/ssl/certs/COMODORSADomainValidationSecureServerCA.crt /etc/ssl/certs/COMODORSAAddTrustCA.crt > /etc/ssl/certs/example.com.certchain.crt
In your webserver use the certchain file as certificate file.