-1

i'm making Angular app which has communication with backend app.

The backend app return me status OK - "200" or few errors, eg. "401, 402, 422", and some others.

I would like to catch the error code and base in it display correct information to end user.

My code is simple:

getClient() {
    this.idHubResponse = this.http.getClient(this.client.clientId).subscribe(
      (data) => {
        this.idHubResponse = data;
      },
      error => {
        console.log(error)
      }
    )
  }

Coule you please help me to make switch base on error code?

Thanks

Ilkar
  • 2,113
  • 9
  • 45
  • 71

1 Answers1

0

Try defining error as HttpErrorResponse and you will be able to access the error code from error.status.

Here is a code snippet:

this.htpp.getClient(this.client.clientId).subscribe({
  next: (data) => {
    console.log(data);
  },
  error: (error: HttpErrorResponse) => {
    switch(error.status) {
      case 401: {
        console.log('401');
        break;
      }
      case 402: {
        console.log('402');
        break;            
      }
      case 422: {
        console.log('422');
        break;
      }
      default: {
        console.log('unknown error');
      }
    }
  }
});
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • I see in the console ERR_CONNECTION_REFUSED but I am unable to access that value using the HttpErrorResponse, most likely because it is a lower level error. However, it is much more informative than the useless information HttpErrorResponse gives in my case. Do you know how I can access the ERR_CONNECTION_REFUSED in Angular? – Brian Reinhold Jun 01 '23 at 13:40
  • ERR_CONNECTION_REFUSED usually indicates that Angular can't establish a connection to the server. Check if the server is running on the correct address and port. Also, check if CORS (Cross-Origin Resource Sharing) is adequately configured or if the firewall is blocking the connection. To access the ERR_CONNECTION_REFUSED error in angular check if error.status === 0 – Miloš Zeljko Jun 02 '23 at 14:59
  • Milos, I understand what the error means. What I am trying to do is capture that error in Angular so I can report it to the user. It is not in the HttpErrorResponse, but I see it on the console. – Brian Reinhold Jun 03 '23 at 23:29
  • Check this link, hopefully it helps: https://stackoverflow.com/questions/41354553/how-to-handle-neterr-connection-refused-in-angular2 – Miloš Zeljko Jun 05 '23 at 07:12
  • Looks like they can't catch the ERR_CONNECTION_REFUSED message, so they do exactly what I do now. I see a status code of 0 and assume that the server could not be reached. VERY unsatisfactory in my opinion. – Brian Reinhold Jun 06 '23 at 08:58