Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core WebApi return error message to AngularJS $http promise

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":

enter image description here

How can I pass the error message to the Angular $http failure promise from Core Web Api?

like image 797
Alex Avatar asked Aug 07 '16 13:08

Alex


Video Answer


1 Answers

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.)

like image 65
Nate Barbettini Avatar answered Sep 23 '22 06:09

Nate Barbettini