Home > Mobile >  type 'String' is not a subtype of type 'Exception' in type cast
type 'String' is not a subtype of type 'Exception' in type cast

Time:08-05

I am using dartz package to return different types from a method, but the problem is I can't return an exception. here is the code below:

      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);
          }
        }
      }

CodePudding user response:

The error occurs because 'e' is a String and you try to cast it as Exception. Just remove "as Exception" and you'll return a String

CodePudding user response:

Make an abstract class like below:

abstract class Failure  {
  final String message;

  const Failure(this.message);
}

Extends abstract class like below:

class ServerFailure extends Failure {
  const ServerFailure(message) : super(message);

}

Lastly, throw an exception like below

return Left(ServerFailure(e.toString()));
  • Related