Search code examples
androidwebviewinternal-server-error

How to handle an "Internal Server Error" with Android WebView?


I'm using onReceivedError to intercept any errors when loading webview. Since our webpage had an Internal Server Error and the whole app is based on webview (no native navigation), it will just look like this:

Example Screenshot

This way I intercept errors:

    @SuppressLint("NewApi")
    public void onReceivedError(final WebView view, WebResourceRequest request, final WebResourceError error) {
        Log.d(TAG, "HTTP error " + error.getErrorCode() + " ---> " + error.getDescription());
        int err = error.getErrorCode();
        if (err == -2) {
            view.loadUrl("about:blank");
            view.loadUrl("file:///android_asset/de_offline.html");
        } else {
            view.reload();
        }
    }

Why didn't the app recognize this Internal Server Error? It recognizes if there's no internet connection.

But this error kinda destroys the whole app, because this screen won't go away, even if the webpage is back online. This means I'm forced to setAppCacheEnabled to false.

I guess that is because it's stored in the cache or the reload button is missing. But since we're on a shared hoster, we can't add an reload button to this html error page.

Even if I fully close the app and start it again, this error will be displayed.

The only option for a user would be uninstalling the app or removing the cache manually, but I don't think anyone would do that or in most cases don't know that.

So my question is why the onReceivedError didn't even load the local de_offline.html asset html page instead? Do I have to intercept at some point earlier and what method or where would that be?


Solution

  • Check that the Error Page is not responded with an HTTP 200 Status code. Server Errors should be responded with HTTP-5xx Status codes. I suspect that the WebView is receiving an HTTP 2xx and "thinks" the response is OK, so your error handling doesn't take place.

    Ref: List of HTTP status codes and their meaning

    Edit: I just looked up on: WebViewClient - Error Code From what I see this describes whole different set of errors. But why?

    Another Edit: Oh my ... what the heck?! As far as I can see there is no way of getting HTTP status codes in a WebView?! This is beyond me. All I could get is this workaround How can I check from Android WebView if a page is a "404 page not found"?. Adapt this for Internal Server Erros (if applicable use the method from Android SDK API Level 23, where an onReceivedHttpError was added)