Bhasyakarulu Kottakota
Bhasyakarulu Kottakota

Reputation: 833

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.

Upvotes: 1

Views: 8644

Answers (1)

UtopiaLtd
UtopiaLtd

Reputation: 2590

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

Upvotes: 3

Related Questions