Angular 4 : get error message in subscribe

Viewed 99140

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,

4 Answers

Sometimes when you call catch without using arrow function like below

getUserList() {
    return this.http.get(this.constURL + '/loans/all', this.headerOptions)
    .catch(this.handleError);
}

handleError(error: Response) {
    if (error.status == 500) {      
      this.router.navigate(['/login']);
    } else {
      return Observable.throw(error);
    }
}

then it gives error of

ERROR TypeError: Cannot read property 'navigate' of undefined not getting this

Because in handleError function this object is not accessible..if you console this.router then you will get undefined.. so this object not working and not getting router all available methods

So you have to use arrow function here like below

getUserList() {
    return this.http.get(this.constURL + '/loans/all', this.headerOptions)
    .catch(error => { 
      return this.handleError(error);
    });
}

handleError(error: Response) {
    if (error.status == 500) {      
      this.router.navigate(['/login']);
    } else {
      return Observable.throw(error);
    }
}

Also if you have not mentioned return for handlerError function then it will throw error again like

Argument of type '(error: any) => void' is not assignable to parameter of type

So its necessary to type return for handlerError function.

Check in details here . He has explained code very well with all possible errors and solution of that..worked for me

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

You can just add err.json() in your callback parameters


this.myService.getUser(this.id).subscribe((customer) => {
  console.log(customer);
  this.customer = customer,
  (err) => {
    const error_response = err.json(); // response body
    console.log(error_response)
  }
});

Related