httpflutterexception

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.


Solution

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