'How do you catch canLaunch exceptions using url_launcher in flutter?

Using the code from the package I was unable to catch the exception. Note that I would like to catch this specific exception.

// from https://pub.dev/packages/url_launcher
_launchURL() async {
  const url = 'myscheme://myurl';
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

// my code
try {
  _launchURL();
}
catch (e)
{
  // although the exception occurs, this never happens, and I would rather catch the exact canLaunch exception
}


Solution 1:[1]

I would try to put the try catch statement inside the function. I believe what is happening is that the try/catch statement is only applying for the function call and although it is async I dont believe that it actually tries and returns exeptions.

So the solution would look somethink like this:

_launchURL() async {
  try{

  const url = 'myscheme://myurl';
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
  }

  catch(e){
  //debug e
  }
}

// my code
launchURL();

Solution 2:[2]

You can use .then() for business logic.

For me, it is used to check if the app can be opened on the device.

Can be solution below,

-->  url_launcher: ^6.0.2
-->  https://pub.dev/packages/url_launcher

launch(appLink).then(
  (bool isLaunch) {
    print('isLaunch: $isLaunch');
    if (isLaunch) {
      // Launch Success
    } else {
      // Launch Fail
    }
  },
  onError: (e) {
    print('onError: $e');
  },
).catchError(
  (ex) => print('catchError: $ex'),
);

Work for me.

Solution 3:[3]

Future<void> _launch(String url) async {
await canLaunch(url)
    ? await launch(url)
    : throw 'Could not launch $url';

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mihoci10
Solution 2 bamossza
Solution 3 M Karimi