Centralized handling for HTTP errors in Angular 4

后端 未结 2 506
一生所求
一生所求 2021-02-06 12:51

I want to inform the user if an HTTP request fails, without having to write additional code for every HTTP request.

I had a working prototype for angular 2:

<         


        
2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-06 13:42

    Another option is simply having a service that delegates to the Http service while adding whatever custom error handling, debugging logic, extra headers etc that you need to interact with your API.

    This service then becomes your centralized point for interacting with anything Http related and as such you can centralize your error handling right there. In any project I develop, I ALWAYS create such a class because practically every single API you interact with has some common configuration that has to happen with every request (even if that configuration is as little as specifying the base url to use).

    Example of such a class:

    export class ApiGateway {
    
      baseURL = "https://myapi.com";  // or sometimes pulled from another file
      constructor(private http: Http) { }
    
      get(path, params) {
        showLoadingIndicator();
    
        let headers = this.createMySpecialHeaders();
        let options = { headers: headers } // and whatever else you need to generalize
        let fullUrl = this.baseUrl + path + '?' + this.urlEncode(params)`;
        return this.get(path, params, options)
                   .do(() => hideLoadingIndicator())
                   .map(res => res.json())
                   .catch(err => {
                        hideLoadingIndicator();
                      // show error message or whatever the app does with API errors etc
                      // sometimes rethrow the error, depending on the use case
                    })
      }
    }
    

    To me, this is basic OOP principles - you wrap your interactions with things outside your control in an adapter class to allow you some protection against external changes and to change the API of that external thing to something you prefer, if necessary.

    With such a class in place, if, for eg, you upgraded to Angular 4 and the means of receiving errors change, you only have one place to change to handle the new error technique.

提交回复
热议问题