Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch ERR_CERT_AUTHORITY_INVALID in javascript

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.

like image 522
brian Avatar asked Dec 02 '19 04:12

brian


1 Answers

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 TypeErrors 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:

  • axios
  • superagent

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.logs to see what kind of errors it reports.

like image 103
Cully Avatar answered Sep 22 '22 13:09

Cully