C# (500) Internal Server Error overrides original exception

Grigoris Loukidis picture Grigoris Loukidis · May 7, 2018 · Viewed 9k times · Source

I am creating an API on C#. When I have an exception I try to send back a helping message, but "The remote server returned an error: (500) Internal Server Error." overrides the original one.

The code on server side is this one

 string authHeader = actionContext.Request.Headers.Authorization.Parameter;

        if (authHeader.Equals(ATOKEN) || authHeader.Equals(BTOKEN))
        {
            //goal reached. Token Authentication is valid.  
        }
        else
        {
            throw new HttpException("Invalid User!");                                  
        }

When I try to handle the exception on client side a cannot find the message "Invalid User"!

Any suggestions on this?

Answer

Rahul picture Rahul · May 7, 2018

Rather use HttpResponseException like below

    var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
    {
        ReasonPhrase = "Invalid User!"
    };
    throw new HttpResponseException(resp);