Home > other >  Flutter how to show a custom exception message in a widget with custom error message
Flutter how to show a custom exception message in a widget with custom error message

Time:11-11

I want to show my custom error message with a custom exception right now, I only get Instance of 'CustomException' it's not showing the custom message.

I have the following

try {
      batch.set(usersRef, user.toJson());
      batch.set(accountsRef, account.toJson());
      return await batch.commit();
    } on FirebaseException catch (error) {
      throw CustomException(
        message: 'Future Error createUser',
        subMessage: error.message.toString(),
      );
    }

My custom exception class

class CustomException implements Exception {
  int? codeNumber;
  String? codeString;
  String message;
  String subMessage;
  CustomException({
    this.codeNumber,
    this.codeString,
    required this.message,
    required this.subMessage,
  });
}

And my widget

}).catchError((error) {
      setState(() {
        _loader = false;
        _errorMessage = error.toString();
      });
    });

CodePudding user response:

You should override the toString() method in your CustomException class and return the message you want to show on an exception if you wish to show your custom message.

Add this to your CustomException class:

class CustomException implements Exception {
  ...

  @override
  String toString() {
    return 'Exception: $message ($subMessage)';
  }
}

Also, you can add a public method to your CustomException class. Then you can call that method on the CustomException object's instance to print the message:

class CustomException implements Exception {
  ...

  String printStack() {
    return 'Exception: $message ($subMessage)';
  }
}

then:

throw CustomException(message: 'Exception title', subMessage: 'Exception description').printStack();

PS: You don't need to implement the Exception class. (Please correct me if I am wrong. )

  • Related