asp.net webapi和Angular 4之间的泛型错误处理

问题描述:

我想将错误从我的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 
    } 

的问题是,如果我检查错误它的“错误”属性为空,消息是“响应失败的网​​址”,并没有自定义标题,但在浏览器的网络选项卡上,我可以看到我的自定义标题错误以及错误。如何从我的角度应用程序访问这些消息?

我的错误处理程序是这样的:

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