flutter 当API调用返回错误时,函数执行不会继续

xoefb8l8  于 2023-04-13  发布在  Flutter
关注(0)|答案(1)|浏览(140)

我有以下功能:

Future<Map<String, dynamic>> login({
  required String identifier,
  required String password,
}) async {
  final response = await post(
    obj: jsonEncode({
      "identifier": identifier,
      "password": password,
    }),
    endpoint: '/api/auth/login',
  );

  await getRequestStatus(response, APIRequest.postAuthLogin);

  try {
    return response.data as Map<String, dynamic>;
  } catch (e) {
    throw GeneralFailure();
  }
}

当我的API调用返回200时,执行下一行。

await getRequestStatus(response, APIRequest.postAuthLogin);

然而,我遇到的问题是,当我的API调用返回200以外的任何值时,整个函数都会停止运行,应用程序将进入下一个代码段。
如果有帮助的话,这就是我调用函数的地方:

try {
  await _authenticationRepository.login(
          identifier: state.identifier.value,
          password: state.password.value,
        );

  emit(
    state.copyWith(
      submissionState: SubmissionState.submissionSuccess,
      message: 'loginSuccess',
    ),
  );
} on IdentifierDoesntExistFailure {
  emit(
    state.copyWith(
      submissionState: SubmissionState.submissionFailure,
      message: 'loginIdentifierDoesntExist',
    ),
  );
} on WrongProviderFailure {
...
} catch (e) {
  emit(
    state.copyWith(
      submissionState: SubmissionState.submissionServerError,
    ),
  );
}

一旦API返回错误,代码立即跳到第

} on IdentifierDoesntExistFailure {

而不是在另一个函数中继续,并且总是在catch()部分结束。
感谢您的任何帮助!

zxlwwiss

zxlwwiss1#

首先,你可以像这样改变login方法中的异常处理:

Future<Map<String, dynamic>> login({
  required String identifier,
  required String password,
}) async {
  ...
  } catch (e) {
    if (e is ApiException) {
      throw e;
    } else {
      throw GeneralFailure();
    }
  }
}

当你想处理异常时,你需要这样做:

try {
  await _authenticationRepository.login(
    identifier: state.identifier.value,
    password: state.password.value,
  );

  emit(
    state.copyWith(
      submissionState: SubmissionState.submissionSuccess,
      message: 'loginSuccess',
    ),
  );
} on ApiException catch (e) {
  // handle the API error here
  if (e is IdentifierDoesntExistFailure) {
    emit(
      state.copyWith(
        submissionState: SubmissionState.submissionFailure,
        message: 'loginIdentifierDoesntExist',
      ),
    );
  } else if (e is WrongProviderFailure) {
    // handle the specific error
  } else {
    // handle any other API errors
  }
} catch (e) {
  // handle any other exceptions here
  emit(
    state.copyWith(
      submissionState: SubmissionState.submissionServerError,
    ),
  );
}

相关问题