Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 619
Kris-I Avatar asked Jul 20 '17 21:07

Kris-I


People also ask

How do you catch an error in RXJS?

The catchError operator takes as input an Observable that might error out, and starts emitting the values of the input Observable in its output Observable. If no error occurs, the output Observable produced by catchError works exactly the same way as the input Observable.

How does Angular handle error in Observable?

Catch errors in the observable stream Another option to catch errors is to use the CatchError Operator. The CatchError Operators catches the error in the observable stream as and when the error happens. This allows us to retry the failed observable or use a replacement observable.

Can we use try catch in Angular?

The good news is, Angular has a kind of global try/catch that we can use in one centralized location to catch all exceptions.

Where do you put catchError?

Always put the “catchError” operator inside a switchMap (or similar) so that it only ends the API call stream and then returns the stream to the switchMap, which continues the Observable.


2 Answers

(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); } 
like image 66
Nehal Avatar answered Oct 03 '22 22:10

Nehal


I asked my friend for help so he told : Well in the component place err.error.message like below >>

 this.myService.getUser(this.id).subscribe((customer) => {   console.log(customer);   this.customer = customer,   (err) => console.log(err.error.message) }); 
like image 30
aniran mohammadpour Avatar answered Oct 03 '22 22:10

aniran mohammadpour