Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch http errors in angular(ionic)?

I'm trying to catch HTTP error with error code 400 using the following code in a ionic4 application. But it fails to catch it, what's wrong in here. None of the console log lines executes, but in firefox console it shows 400 error.

export class AuthService {

  constructor(private httpClient: HttpClient)  {}

  login(email: string, password: string){

    const data = {
      password: password,
      email: email,
    }

    this.httpClient.post(url, data).pipe(
      tap((res: IAuthResponse) => {
        console.log("Catch error 1") 
        return res;
      }),
      catchError((error) => {
        console.log("Catch error 2")
        return Observable.throw(new Error(error.status));
      })
    ).subscribe( 
       (result) => {
         console.log("Catch error 3")
       },
       (error) => {
          console.log("Catch error 4")
       }
    );
  }

enter image description here

Actually i just want to handle this error in any of the place where i coded console.log line. Found many examples like this, but none of them works.

Edit : In my real code this, console log line 1 is in the AuthService class but the subscribe code is in a different class file. Both these classes has to do some initialization based on the results. So I need to have both of pipe code and subscribe code.

like image 550
Sameera K Avatar asked Aug 13 '26 06:08

Sameera K


1 Answers

this is the way that can be done

Here is working Example

this.httpClient.post("ssdsdsd", data).pipe(
      (res: any) => {
        console.log("Catch res ") 
        return res;
      },
    ).subscribe( 
       (result) => {
         console.log("Catch result ")
       },
       (error) => {
          console.log("Catch error ")
       }
    );
like image 165
Chanaka Weerasinghe Avatar answered Aug 14 '26 22:08

Chanaka Weerasinghe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!