1
votes

I am using Angular 1.5 and ASP.Net WebApi 2. I want to show a error message when a $http.get request fails. Unfortunately, the error callback only contains a general status text (e.g. internal server error) but not my specified message. How can I achive that?

Web Api controller:

public IHttpActionResult GetSomething()
{
  try
  {
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(GetContent(...));
    return ResponseMessage(result);
  }
  catch (Exception ex)
  {
    return InternalServerError(ex);
  }
}

Angular call:

$http.get('url')
.then(function (result) {
...            
}, function (error) {
  //$scope.errorMessage= ???
});
1

1 Answers

0
votes

You can create your own result that includes whatever content you want:

public class ServerErrorResult : HttpActionErrorResult
{
    public Exception Exception {get; set;}

    public override Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var content = Content;
        if(Exception != null)
        {
            content += $"\r\nException Details:{Exception.Message}";
        }
        var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
        {
            Content = new StringContent(content),
            RequestMessage = Request;
        };

        return Task.FromResult(response);
    }
}

Then in your controller, you just return this new result instead:

public IHttpActionResult GetSomething()
{
  try
  {
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(GetContent(...));
    return ResponseMessage(result);
  }
  catch (Exception ex)
  {
    return new ServerErrorResult 
        {
            Exception = ex
        };
  }
}

You can also create an extension method on the controller to abstract some of this plumbing away:

public static HttpActionErrorResult ServerError(this ApiController controller, Exception ex)
{
    return new ServerErrorResult 
        {
            Exception = ex
        };
}

And call it from your controller like this:

public IHttpActionResult GetSomething()
{
  try
  {
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(GetContent(...));
    return ResponseMessage(result);
  }
  catch (Exception ex)
  {
      return ServerError(ex);
  }
}

Hope that helps.