c# - How to deal with exception in Windows Phone? -


i have async method in windows phone 8.1, need download file web. of course if there no internet connection, can't do. how can face problem. method one:

public async task<string> getjson(uri url)     {         if (networkinterface.getisnetworkavailable())         {             httpclient client = new httpclient();             string jsonstring = await client.getstringasync(url);             return jsonstring;         }         else         {             await new messagedialog("no internet connection avaliable. please check !").showasync();             return "";         }     } 

should add check of internet connection, before calling getjson(uri url); method ? in case have re-write lines of code in each method, require getjson(uri url); , prefer not this.

update

the code wrote doesn't work, because application crashes in case there no internet connection. solution, don't this:

private async void change(object sender, routedeventargs e)     {          if (networkinterface.getisnetworkavailable())         {             frame.navigate(typeof("page async method"));         }         else         {              await new messagedialog("no internet connection avaliable. please check !").showasync();         }      } 

checking internet connection ok, still might come unavailable after you've done check.

the correct solution catch exception , deal it:

public async task<string> getjson(uri url) {             bool error = false;     if (networkinterface.getisnetworkavailable())     {                 try        {            httpclient client = new httpclient();            string jsonstring = await client.getstringasync(url);            return jsonstring;        }        catch(exception) // more specific exception better        {            error = true;        }     }     else     {         error = true;          }      if (error)     {         await new messagedialog("no internet connection avaliable. please check !").showasync();         return "";     } } 

i handle exception on higher level (ie. caller of getjson())


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -