我使用dartz包从一个方法返回不同的类型,但问题是我不能返回异常。以下代码如下:
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);
return Right(response.body as Map<String, dynamic>);
} catch (e) {
// The error occurs here:
return Left(e as Exception);
}
}
}发布于 2022-08-05 12:49:36
发生错误是因为'e‘是一个字符串,您试图将它转换为异常。只要删除"as Exception“,您就会返回一个字符串
发布于 2022-08-05 12:46:20
创建一个抽象类,如下所示:
abstract class Failure {
final String message;
const Failure(this.message);
}扩展抽象类,如下所示:
class ServerFailure extends Failure {
const ServerFailure(message) : super(message);
}最后,抛出如下所示的异常
return Left(ServerFailure(e.toString()));https://stackoverflow.com/questions/73249888
复制相似问题