0

I have the following code (ok I hard-coded the message) in my Web API controllers:

catch (Exception e)
{
    var errorResponse = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "My Error message");
    throw new HttpResponseException(errorResponse);
}

However, when I look at errorResponse, the ReasonPhrase is "Internal Server Error", my error message is nowhere to be found.

Why is this?

I realise I could build the HttpResponseException manually myself, but... Is there a correct way to do the above? How are others doing similar?

Rob L
  • 2,124
  • 3
  • 22
  • 50
  • 1
    `Internal Server Error` is thrown if it can't tell the specific problem, perhaps, it could be a logical error in your code. In what line this error is thrown? – CodeRed Oct 07 '19 at 01:11
  • This code is in my Controller, the Exception is thrown in a service. Obviously I am the one saying "HttpStatusCode.InternalServerError". What I want is "My Error message" to be passed back to caller of the API function. Not sure if there is a "correct" way. – Rob L Oct 07 '19 at 01:34
  • 1
    I guess what I am trying to ask is... What is the point of the second parameter in Request.CreateErrorResponse(code, message) if it is just going to be ignored? The errorResponse does not contain the message anywhere?! – Rob L Oct 07 '19 at 01:47
  • You probaly want to return the response created with `CreateErrorResponse` rather than throwing an exception with the response in it. Or throw an exception but do not create a response. See also https://stackoverflow.com/questions/12519561/throw-httpresponseexception-or-return-request-createerrorresponse – Peter Bons Oct 07 '19 at 06:10

1 Answers1

0

Had to do it like this in the end. This is the only way I could find to get the error message sent back to the client.

    catch (Exception e)
    {
        return new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.InternalServerError,
            ReasonPhrase = "My error message"
        };
    }
Rob L
  • 2,124
  • 3
  • 22
  • 50