What is the best way to perform Error handling in Angular?

Error is when the request fails on the server or fails to reach the server due to network issues. In this condition, HttpClient returns an error object instead of a successful response. To resolve this issue, we must handle the component by passing the error object as a second callback to the subscribe() method.

See the following example to understand how we handle in the component:

  1. fetchUser() {  
  2.   this.userService.getProfile()  
  3.     .subscribe(  
  4.       (data: User) => this.userProfile = { …data }, // success path  
  5.       error => this.error = error // error path  
  6.     );  
  7. }  

You can write an error message to give the user some meaningful feedback instead of displaying the raw error object returned from HttpClient.