onmyway
onmyway

Reputation: 1515

How to handle errors in Angular component

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!

Upvotes: 1

Views: 101

Answers (2)

Anand Bhushan
Anand Bhushan

Reputation: 783

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

  }

Upvotes: 1

dev-dan
dev-dan

Reputation: 6303

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.

Upvotes: 2

Related Questions