Bhasyakarulu Kottakota Bhasyakarulu Kottakota - 1 month ago 5
ASP.NET (C#) Question

Web API always returns internal server error instead of error which I have thrown

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.

Thanks in advance.

Answer

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