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,
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.
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.
The good news is, Angular has a kind of global try/catch that we can use in one centralized location to catch all exceptions.
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.
(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); }
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) });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With