我想显示我的自定义错误消息与自定义异常现在,我只得到Instance of 'CustomException'
它不显示自定义消息。
我有以下
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(),
);
}
我的自定义异常类
class CustomException implements Exception {
int? codeNumber;
String? codeString;
String message;
String subMessage;
CustomException({
this.codeNumber,
this.codeString,
required this.message,
required this.subMessage,
});
}
和我的小部件
}).catchError((error) {
setState(() {
_loader = false;
_errorMessage = error.toString();
});
});
你应该在你的CustomException
类中覆盖toString()
方法,并返回你想要在异常中显示的消息,如果你想显示你的自定义消息
将此添加到您的CustomException
类:
class CustomException implements Exception {
...
@override
String toString() {
return 'Exception: $message ($subMessage)';
}
}
同样,您可以向CustomException
类添加一个公共方法。然后,您可以在CustomException对象的实例上调用该方法来打印消息:
class CustomException implements Exception {
...
String printStack() {
return 'Exception: $message ($subMessage)';
}
}
:
throw CustomException(message: 'Exception title', subMessage: 'Exception description').printStack();
PS:您不需要实现Exception
类。(如果我说错了,请指正。)