When do functions request, requestError, response, responseError get invoked when intercepting HTTP request and response?

后端 未结 1 977
挽巷
挽巷 2021-01-22 21:20

The documentation mentions you may define 4 functions for an interceptor and it says:

There are two kinds of interceptors (and two kinds of rejection inte

相关标签:
1条回答
  • 2021-01-22 22:06

    Well, as you might expect...

    request interceptors are fired before a request is sent to the server (and of course before the data is transformed using the transformRequest function).

    requestError interceptors are fired when there is a request error, i.e. if any of the previous request interceptors threw an error or returned a promise that get's rejected.

    response interceptors are fired as soon as the response arrives from the server. Note that response interceptors are fired in reverse registration order.

    responseError interceptors are fired when the HTTP status code indicates an error (i.e. it is not a redirect and is outside of the [200-299] range) or when any of the previous response interceptors threw an error or returned a promise that get's rejected.


    A key point is that any of the above methods can return either an "normal" object/primitive or a promise that will resolve with an appropriate value. In the latter case, the next interceptor in the queue will wait until the returned promise is resolved or rejected.

    In this context, throwing an error refers to plain, old JavaScript error. E.g. trying to access a non-existing method (myObj.methodThatDoesNotExit()) or explicitly raising an exception (throw Error()).

    A rejected promise can be created either by returning $q.reject(someObj) or by calling .reject(reason) on the deferred object whose promise was returned.


    As the documents state, it is important that "before you start creating interceptors, be sure to understand the $q and deferred/promise APIs".


    The relevant parts of the source code (v1.2 branch - current version 1.2.16), where interceptors are handled are in ng/http.js:

    line 127 - line 155
    line 685 - line 724

    0 讨论(0)
提交回复
热议问题