2016-12-15 28 views
2

我正在弄一堆Angular2代碼,它與一個返回帶有http錯誤代碼(如404或401)的json的服務器交互。 我找不到一個方法來讀取json錯誤響應。 我無法使用.map(),因爲沒有正常響應的數據。Angular2從錯誤中提取json

return new Promise((resolve, reject: Response) => { 
     this.http.request(new Request(requestoptions)) 
      .subscribe(
      data => {resolve()}, 
      error => { error.json() } //<-- No json() 
     ) 
     }; 

這是怎麼處理的?

+0

檢查[這](https://angular.io/docs/ts/latest/guide/server-communication.html#!#error-handling)如何在Http調用時處理錯誤。 –

+0

try error => console.log(error),錯誤對象響應可能不是json對象。什麼是api發送代碼的樣子? – deek

+0

錯誤代碼包含一個json對象(我​​在瀏覽器的http響應中看到這個) – ApriOri

回答

1

我解決了我的問題,試圖解析只包含響應的http代碼。 此示例代碼可以幫助別人:

return new Promise((resolve, reject) => { 
    this.httpProvider.login(url, credentials) 
    .map(res => { 
     //avoid parsing the response from the server for some requests since it's not a valid json 
     if (res.status >= 400 && res.status < 500) { 
     return res.json(); 
     } 
     else return res; 
    }) 
    .subscribe(
     data => { 
     }, 
     error => { 
     switch (error.status) { 
      case 400: 
      case 401: 
      let erromsg: string = this.parseServerError(error); 
      reject(erromsg); 
      break; 
      case 404: 
      case 500: 
      reject("Server error"); 
      break; 

      default: 
      reject("Network Error"); 
     } 
     } 
    ); 
}); 




parseServerError(error): string { 
    try { 
    let message = error.json().message[0].description; 
    return message; 
    } catch (e) { 
    return "Undefined error"; 
    } 
}