2

Up to now if a web api 2 error happened and I caught it, I'd return a custom object and fill in the error message from the catch. This would however make the actually http.post() go into success method instead of the error and then I'd have to look at my own boolean success variable and if true all good, if false show error. This is kind of annoying as I have to look for errors in 2 different places for 2 different reasons. From Web API 2 is there a way I can make the http.post() trigger the error callback while I fill out the error message if I catch an error in the web api controller?

[HttpPost]
public MyResponseObject UpdateData(RequestObject req)
{
   MyResponseObject resp = new MyResponseObject();
   resp.Success = true;

   try{
      // error happens here
   }catch(Exception ex){
      resp.Success = false;
      resp.Msg = ex.Message;
   }

   return resp;
}

The http.post() call will still be successful but now I have to look in the success callback for my resp.Success to see if it was REALLY successful or not. Sure the API call was able to be made, but something went wrong inside of it. I'd like to just be able to display that message and fail the call so the http.post() error callback is called with the exception message.

user441521
  • 6,942
  • 23
  • 88
  • 160
  • Not catching the exception should trigger this behavior. Or you could catch it, log the useful info, and throw an `HttpResponseException` with an end-user-friendly message. – David Jul 14 '17 at 18:25
  • 1
    Possible duplicate of [How to throw exception in Web API?](https://stackoverflow.com/questions/14607844/how-to-throw-exception-in-web-api) – CodingYoshi Jul 14 '17 at 18:26

1 Answers1

6

Just throw an exception:

throw new HttpResponseException(HttpStatusCode.InternalServerError);

If you want to customize the response that is returned you can create a HttpResponseMessage with more detail:

var response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
    Content = new StringContent("We messed up"),
    ReasonPhrase = "Error"
}
throw new HttpResponseException(resp);

Documentation here

maccettura
  • 10,514
  • 3
  • 28
  • 35