Skip to content
Advertisement

capture error from catchError – http.post

component which is calling submitUser

this.someservice.submitUser(postData).subscribe((data) => {
      this.viewUsers();
    }, (err) => {
      console.log('error in the component', err);
    });

Here is the service file with submitUser function

 public submitUser(reqBody ) {
    return this.httpService.post('roles', reqBody, '/business/create')
    .pipe(
      catchError(
        this.httpService.handleError())
    );
  }

and here is the httpService Post and handleError methods

 public post<JSON>(url: string, body: any, param?: string, options?: IRequestOptions): Observable<JSON> {

    return this.intercept(this.http.post<JSON>(this.getURLFromMethodName(url, param), body, this.requestOptions(options)));
  }
handleError<T> (operation = 'operation', result?: T) {
      return (error: any): Observable<T> => {

        // TODO: send the error to remote logging infrastructure
        console.error('error from httpclient', error); // log to console instead

        throw throwError(new Error(error));
      };
    }

handleError adisplays the console error, I am trying to return/capture this error in my submitUser function in service.ts

How do i do that ? Any Inputs appreciated, Thanks

Advertisement

Answer

Your handleError() method returns an error observable along with logging the error to the console.

When some error occurs, the catchError operator takes that error and gives it to handleError() which in turn returns an error observable.

CASE 1: Returning the error

If you need to pass this error on to the subscriber, you don’t have to do anything. The catchError operator is already taking care of it for you.

With the same code, let’s say some component is consuming your service, then you can just write

someService.submitUser().subscribe((res) => {
   \ handle success
}, (err) => {
   console.error(err); // Will print the error
});

Whenever the error occurs, the catchError is going to return the error observable back to its subscriber and it will go in the error function of the observer as shown in the code snippet above.

CASE 2: Handling the error

The catchError operator accepts a function that takes error as an argument. If you return another observable inside this instead of throwing an error, the subscriber won’t get to know that the error had occurred, the success function of the observer will execute.

// Inside the service

public submitUser(reqBody ) {
  return this.httpService.post('roles', reqBody, '/business/create')
  .pipe(
    catchError((err) => of([1,2,3]));
}


 // Inside the component consuming the service

someService.submitUser().subscribe((res) => {
   console.log(res) // Will print [1,2,3]
}, (err) => {
   \ handle error
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement