You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中AuthService错误处理无法显示API返回的正确提示

解决方案

1. 优化异常处理,提取纯错误信息

当前代码捕获异常后直接使用e.toString(),会包含异常类型前缀(如Exception: ),导致错误信息冗余。建议通过自定义异常类来更精准地传递错误内容:

步骤1:添加自定义认证异常类

在AuthService文件中新增:

class AuthException implements Exception {
  final String message;
  AuthException(this.message);

  @override
  String toString() => message;
}

步骤2:修改登录方法的异常抛出逻辑

将AuthService中login方法里的throw Exception(errorMessage);替换为:

throw AuthException(errorMessage);

步骤3:在登录页面正确捕获异常信息

修改LogInScreen中_onSubmit的catch块:

catch (e) {
  setState(() {
    _errorMessage = e is AuthException ? e.message : 'Unknown error';
  });
}

2. 适配API实际的错误响应结构

显示通用错误的常见原因是API返回的错误字段并非你预期的message。先打印响应内容确认结构:
在AuthService的login方法中,状态码非200时添加打印:

if (response.statusCode != 200) {
  print('Login failed response: ${response.body}'); // 输出实际响应内容
  // ... 原有解析逻辑
}

根据打印结果调整错误字段的获取:

  • 若API返回{"error": "Invalid credentials"},则将responseData['message']改为responseData['error']
  • 若API返回{"error": {"message": "Invalid credentials"}},则改为responseData['error']['message']

3. 处理JSON解析失败的边界情况

如果API返回非有效JSON格式,jsonDecode会抛出异常,导致显示通用错误。添加解析异常捕获:

if (response.statusCode != 200) {
  try {
    final responseData = jsonDecode(response.body);
    final errorMessage = responseData['message'] ?? responseData['error'] ?? 'Unknown error';
    throw AuthException(errorMessage);
  } catch (decodeError) {
    throw AuthException(response.reasonPhrase ?? 'Unknown error');
  }
}

通过以上步骤,即可准确获取并展示API返回的实际错误信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:52:01