在angular2中显示web api异常

时间:2016-07-28 08:06:05

标签: angular asp.net-core jwt

我正在开发一个带有web api后端和angular2前端的项目。我有一个问题,显示angular2中的服务器错误。每次服务器出错时都会抛出CORS错误。

Here is my sample api

public IActionResult Post([FromBody] Visitor model)
{
  if (model == null) throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NoContent)
  {
      ReasonPhrase = "Missing model in post"
  });
  _registerService.register(model);
  return Ok(model);    
}


And here is my angular2 service


addVisit(visit: Visit) {

let siteId = visit.siteId;
let body = JSON.stringify(visit);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

return this.authHttp
    .post(`${this._visitorsUrl}` + siteId, body, options)
    .map(res => {
        res.json();
        console.log("map: " + JSON.stringify(res.json()));
    })
    .catch(err => console.log(err));

}

当模型为null时,它返回错误502或CORS错误,但是当模型不为null时,它将返回200

我的问题是如何显示服务器返回的错误。

3 个答案:

答案 0 :(得分:1)

.net Core 2.2中有一个错误修复,该错误修复了“在发生错误500的情况下未发送任何CORS标头”的错误,该错误会导致CORS错误。

https://github.com/aspnet/AspNetCore/issues/2378

答案 1 :(得分:0)

无法添加类似

的内容
error =>  this.errorMessage = <any>error;

在你检查null的if?我在.subscribe中使用它到.map但我相信它是你想要的东西吗?

答案 2 :(得分:-2)

您应该将响应转换为InternalServerError并返回内容,如下面的代码片段所示

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                ReasonPhrase = "Missing model in post",
                Content = new StringContent("Missing Model in post")
            });

然后,您将能够在angular中看到错误的statusText属性中的错误。