flutter - 如何在颤振中使用 url_launcher 捕获 canLaunch 异常?
问题描述
使用包中的代码我无法捕捉到异常。请注意,我想捕捉这个特定的异常。
// 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
}
解决方案
我会尝试将 try catch 语句放在函数中。我相信正在发生的事情是 try/catch 语句仅适用于函数调用,虽然它是异步的,但我不相信它实际上会尝试并返回异常。
所以解决方案看起来像这样:
_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();
推荐阅读
- java - 如何为线程运行方法编写junit测试用例
- mysql - 如何在sql中使用after插入触发器
- java - 初始化的文件可以为空吗?
- django - 我必须做些什么来更改最初需要使其成为可选的 Django ForeignKey?
- powershell - foreach 如果没有对象以值开头
- c# - 构建后修改WebHost配置,添加新添加文件的内容
- java - 如何构造创建Entry的接口
- c# - Powershell.Invoke() 结果为 0。
- asp.net-core - ASP.NET Core 从正文反序列化,带默认值
- javascript - ref 没有引用数组中的正确项