1

How to catch a no network (no internet connection) error from Rxjs Observable using Angular HttpClient

RXJS Catch error code

  .catch((err: HttpErrorResponse) => {

    if (err.error instanceof Error) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', err.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(`Backend returned code ${err.status}, body was: ${err.error}`);
    }

    // ...optionally return a default fallback value so app can continue (pick one)
    // which could be a default value
    // return Observable.of<any>({my: "default value..."});
    // or simply an empty observable
    return Observable.empty<T>();
  });

Same angular error code

I'm trying to catch errors when the user has no network and is trying to post off an API request. In the code above, it says that err.error instanceof Error would catch any network errors but it doesn't.

Using both Ios and Android simulators, whenever there's no network, I would get a error code of 0 and message, Unknown Error. I can just check when error code 0, then return a no internet connection message but I can never be certain it's actually a network error.

Is there any method to guarantee the error is a no internet connection issue?

Sure I could check for a network before getting or posting api requests, but then all my pages with api requests need to continuously monitor for a network connection.

NeedHelp101
  • 599
  • 1
  • 9
  • 25
  • Error of 0 are a special set. They are trying to say things are not working and we never received an error response. – JWP Sep 15 '20 at 03:53

1 Answers1

1

You could use navigator.onLine as an additional check if you get an error code 0.
Though I'm not sure how reliable this variable is.

Reqven
  • 1,688
  • 1
  • 8
  • 13