Flutter-解决Try catch出现异常:type ‘_TypeError‘ is not a subtype of type ‘Exception‘ in type cast

简介: Flutter-解决Try catch出现异常:type ‘_TypeError‘ is not a subtype of type ‘Exception‘ in type cast

出现场景

使用Dio时,网络请求可能会出现异常,需要用try catch捕获。

捕获代码如下

try {
  var response = await _dio!.get<T>("/list", queryParameters: {"key":"value"});
  print(response.data);
} catch (e) {
  var exception =  e as exception;
  print(exception);
}

网络请求时出现以下异常信息:

[VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: type '_TypeError' is not a subtype of type 'Exception' in type cast

解决方案

因为catch到的e是dynamic,有可能是Exception,有可能是Error,所以无法做强制转换,需要对这两种类型做不同的操作。

我们可以分开处理Exception,或者统一处理时先判断类型.

分开处理(推荐)

try{
} on Exception catch (e){
  /// 捕获的类型是Exception
} on Error catch (e){
  /// 捕获的类型是Error
}

判断类型

try{
  ...
} catch (e){
  if (e is Exception){
    /// 处理Exception
    ...
  } else if (e is Error){
    /// 处理Error
    ...
  }
} 
相关文章
flutter开发中Use ‘const’ with the constructor to improve performance. Try adding the ‘const’ keyword to the constructor invocation.报错如何解决-优雅草卓伊凡
flutter开发中Use ‘const’ with the constructor to improve performance. Try adding the ‘const’ keyword to the constructor invocation.报错如何解决-优雅草卓伊凡
248 1
|
Dart JavaScript 前端开发
Dart或Flutter中解决异常-type ‘int‘ is not a subtype of type ‘double‘
Dart或Flutter中解决异常-type ‘int‘ is not a subtype of type ‘double‘
687 4
Flutter更改主题颜色报错:type ‘Color‘ is not a subtype of type ‘MaterialColor‘
Flutter更改主题颜色报错:type ‘Color‘ is not a subtype of type ‘MaterialColor‘
218 4
|
Android开发
解决Flutter上架Google Play提示Version code 1 has already been used. Try another version code.
解决Flutter上架Google Play提示Version code 1 has already been used. Try another version code.
507 3
|
Dart 开发工具
解决升级Flutter3.0后出现警告Operand of null-aware operation ‘!‘ has type ‘WidgetsBinding‘ which excludes null
解决升级Flutter3.0后出现警告Operand of null-aware operation ‘!‘ has type ‘WidgetsBinding‘ which excludes null
224 1
|
API
Flutter 解决Type ‘MouseCursor‘ not found.
Flutter 解决Type ‘MouseCursor‘ not found.
228 0
|
机器学习/深度学习 Java Android开发
记录一个Flutter运行的异常FAILURE: Build failed with an exception. What went wrong: A problem occurred config
记录一个Flutter运行的异常FAILURE: Build failed with an exception. What went wrong: A problem occurred config
887 0
Flutter的setState的使用注意事项以及报错The method ‘setState‘ isn‘t defined for the type
Flutter的setState的使用注意事项以及报错The method ‘setState‘ isn‘t defined for the type
|
Dart JavaScript
[Flutter]足够入门的Dart语言系列之流程控制语句:中断和异常(continue/break、try...catch)
循环的执行是通过循环条件来控制的,但是,有时我们想要通过额外的条件判断,来决定是否中断执行,或者中断本次循环而继续执行下次及之后的循环;此外,我们需要对于异常情况的处理...
709 0
[Flutter]足够入门的Dart语言系列之流程控制语句:中断和异常(continue/break、try...catch)
|
IDE 开发工具
Waiting for another flutter command to release the startup lock... 异常解决
平时我们在开发flutter过程中,在执行`flutter packages get`命令之后,如果运气不好的,命令没有执行成功的话,我们就会遇到这个错误提示: ``` Waiting for another flutter command to release the startup lock... ```