Angular 4 : get error message in subscribe

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);
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)