Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I intercept http errors with angular2?

Is there an API similar to angular 1.x's Interceptor API?

I want to be able to add interceptors at application startup that will

  • show the login dialog whenever a 401 status code is returned
  • show a generic error message whenever a 5xx status code is returned

for every http request the application makes.

like image 619
Philip Avatar asked Dec 30 '15 00:12

Philip


People also ask

How do you handle error in Angular interceptor?

An error interceptor is a special kind of interceptor used for handling errors that happen when making HTTP requests. Errors come either from the client-side (browser) or the server-side when the request fails for some reason.

How does Angular handle HTTP errors?

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.

What is HTTP interception?

HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response. Keep in mind that the interceptor wants only HTTP requests.

Can Angular have multiple HTTP interceptors?

After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.


1 Answers

You can create your own HTTPConnection that handles error and inject it into the root app component at bootstrap time.

export class CustomHTTPConnection implements Connection
{
}

and then inject it while bootstrapping as follows

bootstrap([provider(Connection,{useClass:CustomHTTPConnection}]);

If you want do not want to provide a custom connection class, you can do it for each individual request as Http returns an observable which as 3 parameters: onNext, onError, onCompleted.

You can use it as follows:

class Component
{
constructor(private httpService:HttpService){
}
onInit(){
 this.httpService.getData().subscribe(
  ()=>{},  //on Next
  ()=>{}   //onError
}
}
like image 71
Jigar Avatar answered Oct 13 '22 12:10

Jigar