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