Catch语句不会在异步函数中捕获调试模式中的抛出错误

问题描述 投票:0回答:1

我不知道为什么当我调试应用程序时,catch语句没有捕获抛出的错误。 这是主要功能:

void main() async {
  final initialState = await persistor.load();
  bool logged = false;

  if (initialState.isLoggedIn) {
    logged = await initialState.silentlyLogin(); // <---- FUNCTION THAT THROWS ERROR
  }
  if (!logged) {
    initialState.logout();
  }
}

这是我的State类的silentlyLogin函数:

Future<bool> silentlyLogin() async {
    try {
      await globals.googleSignIn.signInSilently();
      return true;
    } catch (e) {
      return false;
    }
}

在调试中,googleSignIn.signInSilently函数抛出了一个错误,在这部分代码中:

@override
  dynamic decodeEnvelope(ByteData envelope) {
    // First byte is zero in success case, and non-zero otherwise.
    if (envelope.lengthInBytes == 0)
      throw const FormatException('Expected envelope, got nothing');
    final ReadBuffer buffer = ReadBuffer(envelope);
    if (buffer.getUint8() == 0)
      return messageCodec.readValue(buffer);
    final dynamic errorCode = messageCodec.readValue(buffer);
    final dynamic errorMessage = messageCodec.readValue(buffer);
    final dynamic errorDetails = messageCodec.readValue(buffer);
    if (errorCode is String && (errorMessage == null || errorMessage is String) && !buffer.hasRemaining)
      throw PlatformException(code: errorCode, message: errorMessage, details: errorDetails); // <------ HERE IS THE ERROR
    else
      throw const FormatException('Invalid envelope');
  }

在调试模式下,android studio会阻止throw PlatformException行中的应用程序,但我的catch语句永远不会被捕获,所以我的函数总是返回true。虽然我的捕获声明从未被捕获。

dart flutter try-catch
1个回答
0
投票

异常可能是在本机代码中抛出而根本没有传递给Dart。 Dart无法捕获Java或ObjectivC / Swift异常。该插件需要在Java中捕获它,向Dart发送消息,在Dart中需要抛出人为异常。

也可以看看

© www.soinside.com 2019 - 2024. All rights reserved.