1

I am using HttpClient to invoke this web API

using (var client = new HttpClient(new HttpClientHandler() { Credentials = _credentials }))
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                    
                return await client.PostAsJsonAsync(controlActionPath, entityObject);
            }

Web API controller I am throwing bellow error:

throw new DuplicateNameException("User already exists.");

However web app always getting internal server error instead of DuplicateNameException.

It would be helpful, if someone suggest what will be the best way to get the exact exception back to Web application from Web API.

Matt
  • 1,013
  • 8
  • 16
  • 2
    The exception which you throw in the controller has to be translated into a HTTP message in order to get back to your client. By default, Web API is handling the exception and wrapping it in HTTP status code 500 (Internal server error) and then probably doing something like writing the stacktrace for your exception in the body of the response. I'm not sure about getting the exact exception back in the response without doing something like serializing the exception, returning it, and then deserializing it on the client side. – ivanPfeff Oct 31 '16 at 16:08
  • Could you post the code of Web API Action Method? – Win Oct 31 '16 at 16:20

1 Answers1

3

Because you are throwing an exception, that automatically becomes an internal server error, because it's still in your internal server-side code. You can either create an exception handler like in this answer or you can throw a specific HttpResponseException type as detailed in the Web API documentation on exception handling:

var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
  ReasonPhrase = "User already exists."
};

throw new HttpResponseException(response);
Community
  • 1
  • 1
UtopiaLtd
  • 2,520
  • 1
  • 30
  • 46