0

I'm new on dart programming so I tried to check subtype of exception in switch case nested in a FutureBuilder and I can't have a satisfactory solution...

I tried to check on switch-case but it's not working but when I try in if-else with is it's working...

My custom Exception subtype :

class HttpException implements Exception {
  HttpStatusError status;
  String message;
  HttpException(int statusCode) {
    switch (statusCode) {
      case 400:
        this.status = HttpStatusError.BadRequest;
        this.message = "Bad request";
        break;
      case 401:
        this.status = HttpStatusError.UnAuthorized;
        this.message = "UnAuthorized access ";
        break;
      case 403:
        this.status = HttpStatusError.Forbidden;
        this.message = "Resource access forbidden";
        break;
      case 404:
        this.status = HttpStatusError.NotFound;
        this.message = "Resource not Found";
        break;
      case 500:
        this.status = HttpStatusError.InternalServerError;
        this.message = "Internal server error";
        break;
      default:
        this.status = HttpStatusError.Unknown;
        this.message = "Unknown";
        break;
    }
  }
enum HttpStatusError {
  UnAuthorized,
  BadRequest,
  Forbidden,
  NotFound,
  InternalServerError,
  Unknown
}
if (snapshot.hasError) {
  final error = snapshot.error;
  print(error is HttpException);
  switch (error) {
    case HttpException:
      return Text("http exception";
    case SocketException:
      return Center(child: Text("socket exception"));
   }
   return Center(child: Text("Error occured ${snapshot.error}"));
}

The print instruction : print(error is HttpException); show true value but I don't enter in the case SocketException.

1 Answers1

1

According to Dart language spec this is not possible.

Switch statements in Dart compare integer, string, or compile-time constants using ==. The compared objects must all be instances of the same class (and not of any of its subtypes), and the class must not override ==. Enumerated types work well in switch statements.

In your custom exception you are using integer in the switch case block, which is a valid datatype. But in the bottom code you are trying to switch per type, which is not supported. Maybe you could try to convert those classes to strings, but this would add more complexity.

https://dart.dev/guides/language/language-tour#switch-and-case

Another approach could be to use the pythonic way to implement the switch case. This uses map/dictionary, where the key is the case and the value is what you want to return, probably a provider in your example.

Replacements for switch statement in Python?

Ezequiel
  • 3,477
  • 1
  • 20
  • 28