I would like to return exception message to the AngularJS UI. As a back-end I use ASP.NET Core Web Api controller:
[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;
}
But on Angular side, failure promise sees only status and statusText "Internal server error":
How can I pass the error message to the Angular $http failure promise from Core Web Api?
Unless you're doing some exception filtering, throw new HttpResponseException(message)
is going to become an uncaught exception, which will be returned to your frontend as a generic 500 Internal Server Error.
What you should do instead is return a status code result, such as BadRequestResult
. This means that instead of returning a string, your method needs to return 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);
}
See also: my answer on how to return uncaught exceptions as JSON. (If you want all uncaught exceptions to be returned as JSON, instead.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With