Why do i get "Exception:" when i receive the exception message in dart?

Viewed 3363

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.

3 Answers

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

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.

Quick solution:

.catchError((error){
  print(
    error.toString().substring(11)
  );
});

You cut the first 11 message chars, that is, "Exception: ".

Related