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

1

7

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?

Maxama answered 7/8, 2016 at 13:43 Comment(1)
You return HttpStatusCode.InternalServerError in this code, which is HTTP 500. Instead, you should figure out what error is in jsonHttpResponse and set message to that.Filmer
G
5

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

Goody answered 8/8, 2016 at 2:31 Comment(3)
But what if it's not a bad request? You might get an exception from your backend and that would warrant a 500 (internal server error).Katsuyama
@DanielPrzybylski In that case, you can always throw an exception (or allow an uncaught one to bubble up), which results in 500 Internal Server Error being sent to the client. Or, you can return status code 500 yourself.Goody
That's what I ended up doing already, I'm just not sure when that isn't included as a convenient method. Also, I'm wondering how to embed messages in the HttpResponse the way the HttpResponseException did it in .NET 4.x.Katsuyama

© 2022 - 2024 — McMap. All rights reserved.