The Web Application I am developing needs to fetch data from a number of different IOTs within the local network, e.g.,
const response = await fetch("https://192.168.0.245/api/auto/login", options);
Since it is an https connection, and each IOT carries a self-signed SSL cert, therefore, the fetch() above will throw an error "TypeError: Failed to fetch" (since the cert has not yet been accepted), and the application will show the following in the browser's console
OPTIONS https://192.168.0.245/api/auto/login net::ERR_CERT_AUTHORITY_INVALID
What I need is to be able to catch this error in javascript. Specifically I need to be able to catch different errors like ERR_CERT_AUTHORITY_INVALID, ERR_SSL_PROTOCOL_ERROR or ERR_CONNECITON_REFUSED... etc. so I can show different error messages accordingly.
Unfortunately the fetch() function always throw the same "TypeError: Failed to fetch" exception under all these three different errors above.
Is there anyway I can catch this specific ERR_CERT_AUTHORITY_INVALID exception?
Thank you.
I looked at the fetch pollyfill code, which should function the same as the native browser implementation (though the error messages are different). It doesn't include information about the specific error encountered. There are two lines that throw TypeError
s and they both look like this:
reject(new TypeError('Network request failed'))
So you just get an error message and no other information. And looking at the documentation for TypeError, you don't get any extra information beyond what's available with a simple Exception
. TypeError
is what the spec requires to be thrown in this case.
You might be able to find another library that reports errors more specifically. I searched around a bit, but it's hard to find out whether a library has that feature just from documentation. You'll probably have to try them out and see what kind of error reporting they provide. Here are a couple options:
Or you could try implementing a solution using XMLHttpRequest
directly. The fetch
pollyfill code is a good starting point for that. You could fork that project and add some console.log
s to see what kind of errors it reports.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With