Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch exception in flutter?

This is my exception class. Exception class has been implemented by the abstract exception class of flutter. Am I missing something?

class FetchDataException implements Exception {  final _message;  FetchDataException([this._message]);  String toString() { if (_message == null) return "Exception";   return "Exception: $_message";  } }   void loginUser(String email, String password) {   _data     .userLogin(email, password)     .then((user) => _view.onLoginComplete(user))     .catchError((onError) => {        print('error caught');        _view.onLoginError();     }); }  Future < User > userLogin(email, password) async {   Map body = {     'username': email,     'password': password   };   http.Response response = await http.post(apiUrl, body: body);   final responseBody = json.decode(response.body);   final statusCode = response.statusCode;   if (statusCode != HTTP_200_OK || responseBody == null) {     throw new FetchDataException(       "An error occured : [Status Code : $statusCode]");    }   return new User.fromMap(responseBody); } 

CatchError doesn't catch the error when the status is not 200. In short error caught is not printed.

like image 468
P-RAD Avatar asked Oct 09 '18 12:10

P-RAD


People also ask

How do you get exceptions in flutter?

Handling Exceptions in Flutter The try block contains the code that might possibly throw an exception. The try block must be followed by on or catch blocks, and an optional finally block. The catch block is used to catch and handle any exceptions thrown in the try block.

How do you solve a flutter error?

As stated in the error, "to fix this problem, create a new project by running flutter create -t app and then move the dart code, assets and pubspec. yaml to the new project." What you need to do is run the command line command `flutter create -t app ' (where is the location of the new project.

How do you catch Future error flutter?

That error is handled by catchError() . If myFunc() 's Future completes with an error, then() 's Future completes with that error. The error is also handled by catchError() . Regardless of whether the error originated within myFunc() or within then() , catchError() successfully handles it.


Video Answer


1 Answers

Try

void loginUser(String email, String password) async {   try {     var user = await _data       .userLogin(email, password);     _view.onLoginComplete(user);       });   } on FetchDataException catch(e) {     print('error caught: $e');     _view.onLoginError();   } } 

catchError is sometimes a bit tricky to get right. With async/await you can use try/catch like with sync code and it is usually much easier to get right.

like image 118
Günter Zöchbauer Avatar answered Oct 11 '22 08:10

Günter Zöchbauer