在 Flutter 中抛出异常的最佳实践是什么



在我的代码中处理之前,我有一个异常被抛出多次(相同的错误对象在树中被抛出4次)。

在每次投掷时,flutter将单词Exception:附加到我的错误对象上,因此消息的最终形状是:
Exception: Exception: Exception: Exception: SocketException: OS Error: Connection refused, errno = 111, address = 10.12.7.15, port = 39682

下面是我如何处理异常的一个例子:

getSomeData () async {
try {
await myFunction3();
} catch (e) {
throw Exception(e);
}
}
/*****************************************/
Future<void> myFunction3 () async {
try {
await myFunction2();
} catch (e) {
throw Exception(e);
}
}
/*****************************************/
Future<void> myFunction2 () async {
try {
await myFunction1();
} catch (e) {
throw Exception(e);
}
}
/*****************************************/
Future<void> myFunction1() async {
try {
await dio.get(/*some parameters*/);
}
on DioError catch (e) {
throw Exception(e.error);
}
catch (e) {
throw Exception(e);
}
}

我想以正确的方式抛出Exception(),以便单词Exception:的重复不再出现在我的错误字符串中。

可以重新抛出捕获到的异常,而不是抛出新的异常:

Future<void> myFunction1() async {
try {
await dio.get(/*some parameters*/);
}
on DioError catch (e) {
// do something
rethrow;
}
catch (e) {
// do something
rethrow;
}
}

查看更多:https://dart.dev/guides/language/effective-dart/usage#do-use-rethrow-to-rethrow-a-caught-exception

相关内容

最新更新