1

How do I go about handling errors in my Angular components, instead of in my Angular services?

Currently my errors are caught in my services, but it would be great if the error is returned to the component for ease of logging.

I have done a lot of searching and testing, but cannot find a simple solution that works for me. I am hoping there is a simple solution to modifying my code below (be kind, I am a NEWB ;)).

I have a very straight forward setup:

In my Component:

  ngOnInit() {
    this.orders = this.authService.registerUser().subscribe(response => {
      return response;
    });
  }

In my Service:

  registerUser(user): Observable<any> {
    return this.http
      .post(this.apiUrl + 'users', this.user, httpOptions)
      .pipe(catchError(this.handleError));
  }

  handleError(err) {
    if (err instanceof HttpErrorResponse) {
      // Server Side Error
      return throwError(err);
    } else {
      // Client Side Error
      return throwError(err);
    }
  }

Thank you in advance!

2 Answers 2

2

In your service, set up the request like so, this will then lead you to handle the error within the component and stop the error being dealt with here. If there is an error here it will be passed to component and handled by sub.

registerUser(user): Observable<any> 
{
  return this.http.post(this.apiUrl + 'users', this.user, httpOptions)
    .pipe(map(data => data));
}

In your component

public ngOnInit() 
{
    this.orders = this.authService.registerUser(...).subscribe(response =>
    {
      //success block
    }, error => 
    {
        // this is error block
        console.log(error); // Http error.
    });
}

You can either handle the error within the error block of the subscription or you could call a function from in here which is set up with the logic to handle to the error.

Sign up to request clarification or add additional context in comments.

Comments

1

You can handle the error in your component as well, subscribe takes in three callback functions, 1. success, 2. error, 3. complete. Modify your ngOnInit like this-

 ngOnInit() {
    this.orders = this.authService.registerUser().subscribe(response => {
       // success
    }, (err) => this.handleError(err), // error
    () => console.log('complete')); // complete

  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.