Flutter 自定义异常不抛出

时间:2021-07-06 09:46:28

标签: flutter dart future

我将 Flutter 从 2.0.2 版升级到了 2.2.2 版,现在从 Future 函数抛出的自定义异常没有被捕获。

例如,我得到了这个 Future 函数,在那里我调用另一个 Future 来执行服务器请求并返回响应或在出现错误时抛出自定义异常 (ApiException):

static Future<bool> signUpCustomerRequest(Map<String, dynamic> params) async {
    try {
      // Here we call this Future function that will do a request to server API.
      dynamic _response = await _provider.signUpCustomer(params);

      if (_response != null) {
        updateUserData(_response);

        return true;
      }

      return false;
    } on ApiException catch(ae) {
      // This custom exception is not being catch
      ae.printDetails();

      rethrow;
    } catch(e) {
      // This catch is working and the print below shows that e is Instance of 'ApiException'
      print("ERROR signUpCustomerRequest: $e");
      rethrow;
    } finally {

    }
  }

这是向服务器发出请求并抛出 ApiException 的 Future 函数:

Future<User?> signUpCustomer(Map<String, dynamic> params) async {
    // POST request to server
    var _response = await _requestPOST(
      needsAuth: false,
      path: routes["signup_client"],
      formData: params,
    );

    // Here we check the response...
    var _rc = _response["rc"];

    switch(_rc) {
      case 0:
        if (_response["data"] != null) {
          User user = User.fromJson(_response["data"]["user"]);

          return user;
        }

        return null;
      default:
        print("here default: $_rc");

        // And here we have the throw of the custom exception (ApiException)
        throw ApiException(getRCMessage(_rc), _rc);
    }
  }

在升级到 Flutter 2.2.2 之前,自定义异常的捕获工作得很好。这个 Flutter 版本有什么变化吗?我做错了什么吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

我能够使用以下代码重现您的错误:

class ApiException implements Exception {
  void printDetails() {
    print("ApiException was caught");
  }
}

Future<void> doSomething() async {
  await Future.delayed(Duration(seconds: 1));
  
  throw ApiException();
}

void main() async {
  try {
    await doSomething();
  } on ApiException catch (ae) {
    ae.printDetails();
  } catch (e) {
    print("Uncaught error: $e"); // This line is printed
  }
}

dart sdk 上有一个未解决的问题,我认为这可能与此相关,但我不确定:https://github.com/dart-lang/sdk/issues/45952

无论如何,我可以通过返回 Future.error 来纠正错误,而不是直接抛出错误:

class ApiException implements Exception {
  void printDetails() {
    print("ApiException was caught"); // This line is printed
  }
}

Future<void> doSomething() async {
  await Future.delayed(Duration(seconds: 1));
  
  return Future.error(ApiException());
}

void main() async {
  try {
    await doSomething();
  } on ApiException catch (ae) {
    ae.printDetails();
  } catch (e) {
    print("Uncaught error: $e");
  }
}