2017-10-18 81 views
0

我想將錯誤從我的API傳遞到Angular 4應用程序。問題是,在角邊我沒有看到正確的錯誤消息:像這樣產生asp.net webapi和Angular 4之間的泛型錯誤處理

的Web API錯誤:

 throw new HttpResponseException(
      new HttpResponseMessage(HttpStatusCode.BadRequest) 
      { 
       Headers = {{"errorMessage", "Message in header"}}, 
       Content = new StringContent("Message in body") 
      } 
     ); 

我的角碼是一樣的東西:

return this._http.get<IMyObj[]>(this._serviceUrl) 
     .do(this.handleSuccessResponse) 
     .catch(this.handleErrorResponse); 

    protected handleErrorResponse(err: HttpErrorResponse) { 
     console.info(err); 
     // some logic based on code 
    } 

的問題是,如果我檢查錯誤它的「錯誤」屬性爲空,消息是「響應失敗的網​​址」,並沒有自定義標題,但在瀏覽器的網絡選項卡上,我可以看到我的自定義標題錯誤以及錯誤。如何從我的角度應用程序訪問這些消息?

回答

0

我的錯誤處理程序是這樣的:

private handleError(err: HttpErrorResponse) { 
    // in a real world app, we may send the server to some remote logging infrastructure 
    // instead of just logging it to the console 
    let errorMessage = ''; 
    if (err.error instanceof Error) { 
     // A client-side or network error occurred. Handle it accordingly. 
     errorMessage = `An error occurred: ${err.error.message}`; 
    } else { 
     // The backend returned an unsuccessful response code. 
     // The response body may contain clues as to what went wrong, 
     errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`; 
    } 
    console.error(errorMessage); 
    return Observable.throw(errorMessage); 
} 

注意,它採用了statusmessage性質,而不是error屬性。

+0

在我的客戶端邏輯中,我實際上正在切換狀態,並且對於每個狀態代碼,我正在做一些不同的事情。問題在於err.message是「HTTP http:// localhost:56219/api/v1/test:400 Bad Request的Http失敗響應」,但在響應正文的網絡選項卡中,我可以看到「Message in body」爲以及我可以看到我的自定義標題。我的問題是我如何訪問我的錯誤處理程序中的響應正文(或自定義標題)。 – AlexanderM

+1

你見過這個:https://github.com/angular/angular/pull/18466它說它是固定的。 – DeborahK

+0

可能是非常基本的問題,但是我如何只更新有版本的修正?我嘗試批量更新,但之後有問題:angular/core common和zone.js正在成爲未滿足的依賴項。 – AlexanderM