使用Dartz包遇类型转换错误:无法正确返回异常
解决Dartz中Either返回异常时的类型转换错误
你的问题出在catch块的强制类型转换上:Dart的catch(e)捕获的对象不一定都是Exception类型——它可能是String、Error子类甚至其他任意对象,直接用e as Exception强转就会触发类型不匹配错误。
解决方案
1. 统一将捕获对象包装为Exception
不管捕获到的是什么类型,都将其转为标准的Exception实例,避免类型错误:
catch (e) { return Left(Exception(e.toString())); }
2. 区分捕获Exception与其他错误
如果需要更严谨的错误分类,可以分开捕获明确的Exception和其他类型的错误:
try { // 你的业务代码 } on Exception catch (e) { // 直接返回捕获到的Exception return Left(e); } catch (e) { // 处理非Exception类型的错误,统一包装为Exception返回 return Left(Exception('Unexpected error: $e')); }
额外修复:JSON解析错误
你的代码还有一个潜在问题:response.body是字符串类型,直接用as Map<String, dynamic>强转会报错,必须用jsonDecode解析:
// 替换原Right返回语句 final data = jsonDecode(response.body) as List; // 注意:TheCatAPI的/v1/images/search接口返回的是数组,取第一个元素 return Right(data.first as Map<String, dynamic>);
修改后的完整代码
import 'dart:convert'; import 'package:dartz/dartz.dart'; import 'package:http/http.dart' as http; class CatPhotoApi { String endpoint = 'api.thecatapi.com'; Future<Either<Exception, Map<String, dynamic>>> getRandomCatPhoto() async { try { final queryParameters = { "api_key": "example key", }; final uri = Uri.https(endpoint, "/v1/images/search", queryParameters); final response = await http.get(uri); final data = jsonDecode(response.body) as List; return Right(data.first as Map<String, dynamic>); } on Exception catch (e) { return Left(e); } catch (e) { return Left(Exception('Unexpected error: $e')); } } }
内容的提问来源于stack exchange,提问作者Hama Sabah
相关产品推荐
相关产品推荐

