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
		...
	}
} 

猜你喜欢

转载自blog.csdn.net/adojayfan/article/details/128036972