Forum Xamarin.Android

Access server exception message when InernalServerError occurs, using HttpClient

RajatMaheshwariRajatMaheshwari USMember
edited February 2016 in Xamarin.Android

Hi,

I am using HttpClient in my Android application (on VS2015) to interact with my ASP.Net Web API.
In case of an exception, Api returns a internal server error with a message.

        public IHttpActionResult GetContainer(string id)
        {
            try
            {
                var container = STDXDKModelHelper.GetContainer(id);
                return Ok(container);
            }
            catch (Exception ex)
            {
                **return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));**
            }
        }

I have to access the custom message in android application.

try
{
    HttpClient _client = new HttpClient();
    _client.DefaultRequestHeaders.Clear();
    _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    response = await _client.GetAsync(apiUrl);
    response.EnsureSuccessStatusCode();
    //do something if success
}
catch(HttpRequestException ex)
{
    //find the error message 
}

HttpRequestException only contains the HTTP status code(internal server error) but, does not contain any info about the message.
Is there a way to find the error returned by server or am I doing something wrong.

Any help will be greatly appreciated.

I can get to the error message on using WebRequest for calling the API.

try{
var request = WebRequest.Create(apiUrl);
using (var response = await request.GetResponseAsync() as HttpWebResponse)
                {
                    var resStream = response.GetResponseStream();
                    //do the work
                }
}
catch (WebException ex)
            {
                //if its not a protocol error then there is no point in getting error response stream
                //show the raw error message
                if (ex.Status != WebExceptionStatus.ProtocolError)
                {
                    ShowPopup("Error", ex.Message);
                    return null;
                }
                string error;
                try
                {
                     //if its a protocol error there is a possibility that server returns
                    //a message having info about the error. Try to get the message.
                    //if server did not return a message, we will fall back to display raw error
                    using (var stream = ex.Response.GetResponseStream())
                    {
                        var jsonResponse = (JsonObject)JsonObject.Load(stream);
                        {
                            error = jsonResponse["Message"]; //**This is the message**
                        }
                    }
                    ShowPopup("Error", error);
                }
                catch
                {
                    // server did not return a message. Display raw error
                    ShowPopup("Error", ex.Message);
                }

Answers

  • JamesEshJamesEsh USMember ✭✭

    How did you resolve this issue?

  • instead of using

    return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
    

    I have used below

    var resp = new HttpResponseMessage
                {
                    Content = new StringContent(ex.message)
                };
    throw new HttpResponseException(resp);
    

    then on the client-side use -

    var httpExceptionMessage =  response?.Content?.ReadAsStringAsync().Result;
    

    the **Result **property holds the http response exception message.

Sign In or Register to comment.