2016-08-26 1 views
0

Я получил эту factory, что я выдвигаю в $httpProviderinterceptorsКак получить доступ к телу ответа от Углового HTTP-перехватчика при сбое?

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 > Вкладка «Сеть», выбирая неудачную XHR и вкладку «Ответ», я получаю следующее:

{"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 "отображаются в моем сообщении о статусе, но это не происходит. Как я могу это показать?

ответ

0

Вместо того, чтобы получить доступ к .DATA свойства содержания ответа, который вы читаете в свойстве его статуса заголовка ответа. statusText похоже на описание кода состояния ответа, more here.

Scripted рабочий образец: 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); 
} 
Смежные вопросы