我想将异常消息返回给AngularJS UI.
作为后端,我使用ASP.NET Core Web Api控制器:
作为后端,我使用ASP.NET Core Web Api控制器:
[Route("api/cars/{carNumber}")] public string Get(string carNumber) { var jsonHttpResponse = _carInfoProvider.GetAllCarsByNumber(carNumber); if (jsonHttpResponse.HasError) { var message = new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(jsonHttpResponse.ErrorMessage) }; throw new HttpResponseException(message); } return jsonHttpResponse.Content; }
但在Angular方面,失败承诺只能看到状态和statusText“内部服务器错误”:
如何将错误消息传递给Core Web Api的Angular $http失败承诺?
解决方法
除非你正在做一些
exception filtering,否则抛出新的HttpResponseException(消息)将成为未捕获的异常,它将作为通用500内部服务器错误返回到您的前端.
您应该做的是返回状态代码结果,例如BadRequestResult.这意味着您的方法不需要返回字符串,而是需要返回IActionResult:
[Route("api/cars/{carNumber}")] public IActionResult Get(string carNumber) { var jsonHttpResponse = _carInfoProvider.GetAllCarsByNumber(carNumber); if (jsonHttpResponse.HasError) { return BadRequest(jsonHttpResponse.ErrorMessage); } return Ok(jsonHttpResponse.Content); }
另请参阅:我在how to return uncaught exceptions as JSON的答案.(如果您希望将所有未捕获的异常作为JSON返回.)