Angular HTTP Error Handling

In this guide, we learn about Angular HTTP Error Handling. Whenever the error occurs in an HTTP operation, the Angular wraps it in an httpErrorResponse Object before throwing it back. We catch the httpErrorResponse either in our component class or in the data service class or globally. The Global HTTP error handling is done using the Angular HTTP Interceptor.

Suggested Reading: Error Handling in Angular

HttpErrorResponse

The HttpClient captures the errors and wraps it in the generic HttpErrorResponse, before passing it to our app. The error property of the HttpErrorResponse contains the underlying error object. It also provides additional context about the state of the HTTP layer when the error occurred.

The HTTP errors fall into two categories. The back end server may generate the error and send the error response. Or the client-side code may fail to generate the request and throw the error (ErrorEvent objects).

The server might reject the request for various reasons. Whenever it does it will return the error response with the HTTP Status Codes such as Unauthorized (401), Forbidden (403), Not found (404), internal Server Error (500), etc. The Angular assigns the error response to error property of the HttpErrorResponse.

The client-side code can also generate the error. The error may be due to a network error or an error while executing the HTTP request or an exception thrown in an RxJS operator. These errors produce JavaScript ErrorEvent objects. The Angular assigns the ErrorEvent object to error property of the HttpErrorResponse.

In both the cases, the generic HttpErrorResponse is returned by the HTTP Module. We will inspect the error property to find out the type of Error and handle accordingly.

Catching Errors in HTTP Request

We can catch the HTTP Errors at three different places.

  1. Component
  2. Service
  3. Globally

Catch Errors in Component

Refer to our tutorial on Angular HTTP Get Request. We created a GitHubService, where we made a GET request to the GitHub API to get the list of Repositories. The following is the getRepos() method from the service. We have intentionally changed the URL (uersY) so that it will result in an error.

We subscribe to the httpClient.get method in the component class

The subscribe method has three callback arguments.

The observable invokes the first callback success, when the HTTP request successfully returns a response. The third call back completed is called when the observable finishes without any error.

The second callback error, is invoked when the HTTP Request end in an error. We handle error here by figuring out the type of error and handle it accordingly. It gets the error object which is of type HttpErrorResponse.

Catch Errors in Service

We can also catch errors in the service, which makes the HTTP Request using the catchError Operator as shown below. Once you handle the error, you can re-throw it back to the component for further handling.

Catch error globally using HTTP Interceptor

The type of error we may encounter vary. But some of those errors are common to every HTTP request. For Example

  1. You are unauthorized to access the API Service,
  2. You are authorized, but forbidden to access a particular resource
  3. The API End Point is invalid or does not exist
  4. Network error
  5. Server down

We can check all these errors in the service or in component, but our app may contain many such service or components. Checking for common errors in each and every method is inefficient and error-prone.

The Right thing to do is to handle only the errors specific to this API call in this component/service and move all the common errors to one single place. This is where we use the HTTP Interceptor.

The HTTP Interceptor is a service, which we create and register it globally at the root module using the Angular Providers. Once defined, it will intercept all the HTTP requests passing through the app. It intercepts when we make the HTTP request and also intercepts when the response arrives. This makes it an ideal place to catch all the common errors and handle it

We create the Interceptor by creating a Global Service class, which implements the HttpInterceptor Interface. Then we will override the intercept method in that service.

The following code shows a simple GlobalHttpInterceptorService

The caching of the Error is done using the catchError RxJS operator. We then re-throw it to the subscriber using the throwError

The catchError is added to the request pipeline using the RxJs pipe operator . When the error occurs in the HTTP Request it is intercepted and invokes the catchError. Inside the catchError you can handle the error and then use throwError to throw it to the service.

We then register the Interceptor in the Providers array of the root module using the injection token HTTP_INTERCEPTORS. Note that you can provide more than one Interceptor (multi: true).

HTTP Error Handling

Next, step is what to do with the errors

The server-side errors return status codes, we can take appropriate actions based on that. For Example for Status code 401 Unauthorized, we can redirect the user to the login page, for 408 Request Timeout, we can retry the operation, etc.

The following example code shows how to check for status codes 401 & 403 and redirect to the login page.

For Server errors with status codes 5XX, you can simply ask the user to retry the operation. You can do this by showing an alert box or redirect him to a special page or show the error message at the top of the page bypassing the error message to a special service AlertService.

For other errors, you can simply re-throw it back to the service.

You can further handle the error in service or throw it back to the component.

The component must display the error message to the user. You can also throw it back to a global error handler in Angular.

HTTP Error handling example

The complete code of this example

app.component.html

app.component.ts

github.service.ts

global-http-Interceptor.service.ts

global-error-handler.service.ts

app.module.ts

app-routing.module.ts

Angular HTTP Error Handling Example

References

HttpErrorResponse

Summary

Using HTTP Interceptors you can catch HTTP Errors and handle it appropriately. Check the HTTP status codes and take appropriate actions like redirecting to the login page, or redirecting to an error page or else throw the error back to the subscriber for further handling of the error.

10 thoughts on “Angular HTTP Error Handling”

  1. SO frustrating that this was written ~3 months ago, but apparently the .subscribe() signature is already deprecated!

  2. I liked the perspective taken here towards error handling. Clicked through a large(?) portion of the Angular material. Very neatly organized, liked it. But the lack of indexing is painful. Clicking through arrow after arrow reminded me the audio cassette of old days. Good luck! 🙂

  3. I liked the perspective taken here towards error handling. Clicked through a large(?) portion of the Angular material. Very neatly organized, liked it. But the lack of indexing is painful. Clicking through arrow after arrow reminded me the audio cassette of old days. Good luck! 🙂

    1. I liked the perspective taken here towards error handling. Clicked through a large(?) portion of the Angular material. Very neatly organized, liked it. But the lack of indexing is painful. Clicking through arrow after arrow reminded me the audio cassette of old days. Good luck!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top