ASP.NET Core WebApi returns error message in AngularJS $ http prom

I would like to return an exception message to the AngularJS user interface. As a back-end, I use the 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 the Angular side, the failure failure sees only the status and statusText "Internal server error":

enter image description here

How to pass error message on Angular $ http rejection of Core Web Api?

+4
source share
1 answer

If you do not filter exceptions , it throw new HttpResponseException(message)will become an uncaught exception, which will be returned to your interface as a common internal server 500 error.

, 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);
}

. : JSON. ( , JSON, .)

+3

Source: https://habr.com/ru/post/1650458/


All Articles