Search code examples
angulartypescript

Angular 4 : get error message in subscribe


In the service, there is this code :

  getUser(id){
    return this.http.get('http:..../' + id)
      .map(res => res.json());
  }

In the component :

this.myService.getUser(this.id).subscribe((customer) => {
  console.log(customer);
  this.customer = customer,
  (err) => console.log(err)
});

When it's the 'customer' exist, no problem I get all the information about the customer.

When the id does not exist, the web api return 'BadRequest' with a message. How can I get this message ? the status ?

Thanks,


Solution

  • Update (with RxJs 6.x.x & Angular v14+):

    Subscribing to service and capturing error response:

    this.myService.getUser(this.id).subscribe({
      next: (customer) => {
        console.log(customer);
        this.customer = customer,
      }, error: (err) => {console.log(err)}
    });
    

    To get the error msg back, add a catchError pipe that will return the error object:

    // import { catchError, switchMap } from 'rxjs/operators';
    ...
    ...
    
    getUser(id){
      return this.http.get('http:..../' + id)
        .pipe(
          catchError(this.handleError)
        );
    }
    
    private handleError(error: HttpErrorResponse) {
      return throwError(() => error);
    }
    

    Original (with RxJs v5.x.x):

    (err) needs to be outside the customer fat arrow:

    this.myService.getUser(this.id).subscribe((customer) => {
      console.log(customer);
      this.customer = customer,
    },
    (err) => {console.log(err)});
    

    To get the error msg back, add a catch that will return the error object:

    getUser(id){
      return this.http.get('http:..../' + id)
        .map(res => res.json())
        .catch(this.handleError);
    }
    
    private handleError(error: any) { 
      let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
      return Observable.throw(error);
    }