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?

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. Commented Aug 7, 2016 at 13:57

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.