envyM6 envyM6 - 6 months ago 41
JSON Question

Exception Handling in UWP

I've got an Async method that calls an API to retrieve a JSON via

HttpClient
with the following code block-

//Assemble the url
string url = "https:someapi.com";
//Call API
var http = new HttpClient();
var response = new HttpResponseMessage();
try
{
response = await http.GetAsync(url);
}
catch (HttpRequestException exception)
{
//The server name or address could not be resolved
var dialog = new MessageDialog("The server name or address could not be resolved!");
dialog.Title = "API Response";
dialog.Commands.Add(new UICommand { Label = "Ok", Id = 0 });
var res = await dialog.ShowAsync();
if ((int) res.Id == 0)
{
exception.ExceptionHandled = true;// Cant' do this!
}
}
return result;


This is for an app development. I was trying to make to app more robust so that while there is no internet or data connection the app should should return that it can't call to the API service and show an error rather than crashing. But I just can't find an way to set the
ExceptionHandled
property to
true
. Is there a better way to do this?
P.S. The app crashes and debugger breaks when
Ok
button is clicked

Answer

You can use the IsSuccessStatusCode property from HttpClient to validate if it is a successful http response. Instead of catching a HttpRequestException, you can handle the failure in the else statement.

try
{
  response = await http.GetAsync(url);
  if(response.IsSuccessStatusCode)
  {
         //handle success
  }
  else
  {
        //handle failure   
  }
}
finally
{
  http.Dispose();
}

Furthermore, a rule of thumb is when you use an IDisposable object, you need to wrap it inside a using statement or handle the dispose in the finally block

using(var http = HttpClient())
{
try
{
  response = await http.GetAsync(url);
  if(response.IsSuccessStatusCode)
  {
         //handle success
  }
  else
  {
        //handle failure   
  }
 }
}