如何在扑扑中捕捉异常? [英] How to catch exception in flutter?

查看:91
本文介绍了如何在扑扑中捕捉异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的异常类.异常类已经由flutter的抽象异常类实现.我想念什么吗?

This is my exception class. Exception class has been implemented by 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);
}

当状态不是200时,CatchError不会捕获错误.捕获的Inshort错误不会打印.

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

推荐答案

尝试

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有时很难正确设置. 借助async/await,您可以像使用同步代码一样使用try/catch,通常更容易解决问题.

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.

这篇关于如何在扑扑中捕捉异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆