Search code examples
angulartypescriptionic-frameworkhttpclient

How to properly handled httpClient?


This is my current code,

service.ts

export class ApiServiceFunction {
    constructor(
        private http: HttpClient
    ) { }

    // in app.ts for test connection
    testConnection() {
        return this.http.get(`${environment.apiUrl}/connection`)
        .pipe(
            catchError(err => {
                console.log('Handling error locally and rethrowing it...', err);
                return throwError(err);
            })
        );
    }
}

component.ts

  private testConnection() {
    this.ApiServiceFunction.testConnection()
    .subscribe(
      data => {
        console.log('data ', data)
      },
      error => {
        console.log('error ',error)

      },
    );
  }

Error shows in console

Handling error locally and rethrowing it... Unknown Error

app.component.ts:190 error Unknown Error

zone-evergreen.js:2845 GET http://172.16.0.115:8080/connection net::ERR_INTERNET_DISCONNECTED

I want to get the error test "ERR_INTERNET_DISCONNECTED"


Solution

  • we can handle it manually.

    You should add the method that gives us user status

    then in catchError block handle behavior

        get isOnline() {
            return navigator.onLine;
        }
    
        testConnection() {
            return this.http.get(`${environment.apiUrl}/connection`)
                .pipe(catchError(e => {
                    if (!this.isOnline) {
                        return throwError('ERR_INTERNET_DISCONNECTED')
                    }
                    return throwError(e)
                })
        }