You need to enable JavaScript to run this app. Flutter异步Future中Catch块未触发,如何实现错误从Repo到Cubit再到UI传递
优惠活动
大模型
产品
解决方案
定价
更多

Flutter异步Future中Catch块未触发,如何实现错误从Repo到Cubit再到UI传递

解决Repository异常无法传递到Cubit并展示到UI的问题

问题根源

Repository层的catch块捕获异常后,没有将异常重新抛出,导致上层Cubit无法感知到错误,自然触发不了自身的catch逻辑。

解决方案步骤

1. 修改Repository,让异常向上传递

有两种方式实现:

方式一:直接重抛原始异常

适合不需要对错误信息做业务转换的场景:

Future<void> register({
  required String email,
  required String password,
}) async {
  try {
    await _firebaseAuth.createUserWithEmailAndPassword(
      email: email,
      password: password,
    );
  } catch (e) {
    // 捕获后重新抛出,让上层Cubit处理
    rethrow;
  }
}

方式二:自定义业务异常(推荐)

把Firebase的底层错误转换成用户友好的业务提示,同时保留异常传递链:

首先定义自定义异常类:

class AuthException implements Exception {
  final String message;

  AuthException(this.message);

  @override
  String toString() => message;
}

然后修改Repository的register方法,根据Firebase错误码封装成业务异常:

Future<void> register({
  required String email,
  required String password,
}) async {
  try {
    await _firebaseAuth.createUserWithEmailAndPassword(
      email: email,
      password: password,
    );
  } on FirebaseAuthException catch (e) {
    String errorMessage;
    // 根据Firebase错误码映射成友好提示
    switch (e.code) {
      case 'email-already-in-use':
        errorMessage = '该邮箱已被注册';
        break;
      case 'invalid-email':
        errorMessage = '邮箱格式不正确';
        break;
      case 'weak-password':
        errorMessage = '密码至少需要6位字符';
        break;
      default:
        errorMessage = '注册失败,请稍后重试';
    }
    // 抛出自定义异常
    throw AuthException(errorMessage);
  } catch (_) {
    // 处理其他未知异常
    throw AuthException('注册失败,请稍后重试');
  }
}

2. 修改Cubit,将错误信息存入State

首先给RegisterState类增加错误信息字段,方便UI读取:

class RegisterState {
  final RegisterStatus status;
  final String email;
  final String password;
  final String? errorMessage; // 新增错误信息字段

  RegisterState({
    required this.status,
    required this.email,
    required this.password,
    this.errorMessage,
  });

  RegisterState copyWith({
    RegisterStatus? status,
    String? email,
    String? password,
    String? errorMessage,
  }) {
    return RegisterState(
      status: status ?? this.status,
      email: email ?? this.email,
      password: password ?? this.password,
      errorMessage: errorMessage ?? this.errorMessage,
    );
  }
}

然后修改Cubit的registerWithCredentials方法,捕获异常并更新状态:

Future registerWithCredentials() async {
  if (state.status == RegisterStatus.loading) return;
  // 开始请求时清除之前的错误信息
  emit(state.copyWith(status: RegisterStatus.loading, errorMessage: null));
  try {
    await _authRepository.register(email: state.email, password: state.password);
    emit(state.copyWith(status: RegisterStatus.success));
  } on AuthException catch (e) {
    debugPrint('注册异常: ${e.message}');
    // 将错误信息存入状态
    emit(state.copyWith(
      status: RegisterStatus.error,
      errorMessage: e.message,
    ));
  } catch (e) {
    // 兜底处理未知异常
    emit(state.copyWith(
      status: RegisterStatus.error,
      errorMessage: '注册失败,请稍后重试',
    ));
  }
}

如果用方式一直接重抛原始异常,Cubit的catch逻辑可简化为:

Future registerWithCredentials() async {
  if (state.status == RegisterStatus.loading) return;
  emit(state.copyWith(status: RegisterStatus.loading, errorMessage: null));
  try {
    await _authRepository.register(email: state.email, password: state.password);
    emit(state.copyWith(status: RegisterStatus.success));
  } catch (e) {
    debugPrint('注册异常: $e');
    emit(state.copyWith(
      status: RegisterStatus.error,
      errorMessage: e.toString(),
    ));
  }
}

3. UI层展示错误信息

通过BlocBuilder监听状态变化,当状态为error且存在错误信息时展示:

BlocBuilder<RegisterCubit, RegisterState>(
  builder: (context, state) {
    return Column(
      children: [
        // 邮箱、密码输入框
        if (state.status == RegisterStatus.error && state.errorMessage != null)
          Padding(
            padding: const EdgeInsets.only(top: 8.0),
            child: Text(
              state.errorMessage!,
              style: TextStyle(color: Colors.red, fontSize: 14),
            ),
          ),
        ElevatedButton(
          onPressed: state.status == RegisterStatus.loading 
              ? null 
              : () => context.read<RegisterCubit>().registerWithCredentials(),
          child: state.status == RegisterStatus.loading 
              ? CircularProgressIndicator(color: Colors.white) 
              : Text('注册'),
        ),
      ],
    );
  },
)

内容的提问来源于stack exchange,提问作者Ibramazin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 09:45:33