【问题标题】:How to access Response body from Angular HTTP Interceptor on failure?如何在失败时从 Angular HTTP 拦截器访问响应正文?
【发布时间】:2016-08-27 03:19:27
【问题描述】:

我有这个factory,我正在推送到$httpProvider interceptors

function httpErrorHandler($q) {
    return {
        'responseError': function (response) {
            if (response.status === 500) {
                if (response.data && response.data.html) {
                    var msg = angular.fromJson(response.data.html).Data;
                    showStatusMessage(msg, 'error'); // assume available
                } else {
                    showStatusMessage(response.statusText, 'error');
                }
            }
            // Always reject (or resolve) the deferred you're given
            return $q.reject(response);
        }
    };
}

和拦截器代码:

function config($httpProvider) {
    $httpProvider.interceptors.push('HttpErrorHandler');
}

当我从服务器收到失败的响应时,查看 Chrome DevTools > Network 选项卡,选择失败的 XHR 和 Response 选项卡,我得到了:

{"Success":false,"Data":"Error Code 0000-229566."}

状态消息中显示的是response.statusText

为了尽量完整,这里是响应标头:

Cache-Control:no-cache, no-store, must-revalidate
Content-Length:110
Content-Security-Policy:frame-ancestors 'self'
Content-Type:application/json; charset=utf-8
Date:Fri, 26 Aug 2016 16:26:11 GMT
Expires:-1
Pragma:no-cache
Strict-Transport-Security:max-age=31536000; includeSubDomains
X-Content-Type-Options:nosniff
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN

我希望在我的状态消息中显示“错误代码 000-1234”,但它没有出现。我怎样才能让它显示出来?

【问题讨论】:

    标签: javascript angularjs angular-http-interceptors


    【解决方案1】:

    您正在读取响应标头的 statusText 属性,而不是访问响应内容的 .Data 属性。 statusText 似乎是响应状态代码的描述,more here。

    编写了一个工作示例:https://embed.plnkr.co/xz54Mh2zGguHB0cLquGE/ 我的错误消息属性是 .status_message 而不是 .Data

    responseError: function (response) {
    /* 
        NOTE: if "status_message" is not in the parsing string JSON.parse(response.data.html).status_message 
        will thrown an undefined error and break the execution
    */
    var msg = !response.data ? 'Error occured ...'
        : !response.data.html ? response.data.status_message : JSON.parse(response.data.html).status_message;
    $alert.show(msg, 'danger');
    
    return $q.reject(response);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-09
      • 1970-01-01
      • 2022-01-19
      • 2018-07-08
      相关资源
      最近更新 更多