Reputation: 1375
Hi I am new to the dart and flutter framework.
I am throwing error like below from my service class where i am calling the API.
if(res["status"]!=200) throw new Exception("Invalid User");
and receiving in presenter class like below and printing
.catchError((Object error){
print(error);
});
I am expecting the result as "Invalid User", but am getting with additional word like "Exception: Invalid User". Can you please explain me why this additional word 'Exception' is coming? and how can i get only the string which i am passing.
Upvotes: 23
Views: 10214
Reputation: 31
You can create an extension function in dart as
extension FormattedMessage on Exception {
String get getMessage {
if (toString().startsWith("Exception: ")) {
return toString().substring(11);
}else {
return toString();
}
}
}
After that you can simply call
exception.getMessage;
to get your exception message without having to implement the Exception class or show the user how the exception is being substring.
Upvotes: 3
Reputation: 96
Use ErrorDescription
throw ErrorDescription(response['error']);
It still acts as an error but you don't get the "Exception" infront of the error
Upvotes: 5
Reputation: 135
Quick solution:
.catchError((error){
print(
error.toString().substring(11)
);
});
You cut the first 11 message chars, that is, "Exception: ".
Upvotes: 2
Reputation: 1997
You can use the message
property of the Exception object
.catchError((error){
print(error.message);
});
This should output Invalid User
I hope this is what you are looking for.
Upvotes: 1
Reputation: 34210
Surprisingly that's how written in exception toString code.
String toString() {
if (message == null) return "Exception";
return "Exception: $message"; // your message will be appended after exception.
}
If you want to avoid this then you have to create custom exception like below:
class HttpException implements Exception {
final String message;
HttpException(this.message); // Pass your message in constructor.
@override
String toString() {
return message;
}
}
Upvotes: 32