TheBoubou
TheBoubou

Reputation: 19903

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,

Upvotes: 44

Views: 121143

Answers (5)

Prashant M Bhavsar
Prashant M Bhavsar

Reputation: 1164

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

Upvotes: 1

Nehal
Nehal

Reputation: 13307

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

Upvotes: 70

Yuno
Yuno

Reputation: 23

Accepted answer is deprecated: https://rxjs.dev/deprecations/subscribe-arguments

Here is for newer versions at the moment of this post:

this.service.getFoo(ID).subscribe({
    next: (result) => {
        this.foo = result;
        /* ... */
    },

    error: (error) => {
        // throw error;
        throw error.message;
    },
})

Upvotes: 1

Aditya Eka
Aditya Eka

Reputation: 1

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

Upvotes: 0

aniran mohammadpour
aniran mohammadpour

Reputation: 161

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

Upvotes: 1

Related Questions