How to catch exception in flutter?

前端 未结 3 610
别跟我提以往
别跟我提以往 2020-12-31 01:06

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

class FetchDataException          


        
相关标签:
3条回答
  • 2020-12-31 01:50

    To handle errors in an async and await function, use try-catch:

    Run the following example to see how to handle an error from an asynchronous function.

    Future<void> printOrderMessage() async {
      try {
        var order = await fetchUserOrder();
        print('Awaiting user order...');
        print(order);
      } catch (err) {
        print('Caught error: $err');
      }
    }
    
    Future<String> fetchUserOrder() {
      // Imagine that this function is more complex.
      var str = Future.delayed(
          Duration(seconds: 4),
          () => throw 'Cannot locate user order');
      return str;
    }
    
    Future<void> main() async {
      await printOrderMessage();
    }
    

    Within an async function, you can write try-catch clauses the same way you would in synchronous code.

    0 讨论(0)
  • 2020-12-31 01:55

    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.

    0 讨论(0)
  • 2020-12-31 01:58
    Future < User > userLogin(email, password) async { try {
      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); }
       catch (e){
        print(e.toString());
    }
    
    0 讨论(0)
提交回复
热议问题