Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 603
Bala Avatar asked Sep 12 '25 03:09

Bala


2 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;
  }
}
like image 67
Jitesh Mohite Avatar answered Sep 14 '25 17:09

Jitesh Mohite


Use ErrorDescription

throw ErrorDescription(response['error']);

It still acts as an error but you don't get the "Exception" infront of the error

like image 26
Specks Dude Avatar answered Sep 14 '25 17:09

Specks Dude