403 error not caught by catchError function Angular 7

Viewed 699

I wrote the below code an when I ran the code in the browser, the login api is giving 403 response code. But I am not able to catch that error and console log it. Can anyone please tell me what is wrong in my code.

 this.http

    .post("login", {

      username,
      password
    }).pipe(
      catchError(err => {
        console.log('Handling error locally and rethrowing it...', err);
        return throwError(err);
      })
    )
    .subscribe(
      (response: any) => {
       }
       error=> {

        console.log(error);

       }
    )
1 Answers

try something like this below:

let params = {
          "login_id" : id,
          "password" : pass
        };

    this.http.post(loginUrl, params, {observe:'response'}).subscribe((data:any) => {
        console.log('http login -> ', data);
      }, (err : HttpErrorResponse) => {
        console.log('http login error -> ', err);
      });
    }

or try this one too :

this.http.post("login", {
      username,
      password
    })
    .pipe(catchError(this.errorMgmt))
    .subscribe(
      (response: any) => {
        console.log('res',response)
       }
    )

  errorMgmt(error: HttpErrorResponse) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      // Get client-side error
      errorMessage = error.error.message;
      console.log('err',errorMessage);
    } else {
      // Get server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${JSON.stringify(error.error)}`;
      console.log('err',errorMessage);
    }
    console.log('errorMgmt -> ',(errorMessage));
    return throwError(errorMessage);
  }
Related