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

Flutter:如何在Widget中展示自定义Exception的自定义错误信息

自定义Exception无法显示自定义消息的解决办法

问题根源

你看到Instance of 'CustomException'是因为默认的toString()方法只会返回对象类型信息,你的自定义异常类没重写这个方法,也没在捕获时直接读取它的属性值。

方案1:重写CustomException的toString()方法

修改你的自定义异常类,添加toString()方法,把需要展示的错误信息拼接返回:

class CustomException implements Exception {
  int? codeNumber;
  String? codeString;
  String message;
  String subMessage;
  CustomException({
    this.codeNumber,
    this.codeString,
    required this.message,
    required this.subMessage,
  });

  @override
  String toString() {
    String errorInfo = '$message: $subMessage';
    // 可选:追加错误码信息
    if (codeNumber != null) errorInfo += ' (错误码: $codeNumber)';
    if (codeString != null) errorInfo += ' (错误标识: $codeString)';
    return errorInfo;
  }
}

这样修改后,原来Widget里的error.toString()就能直接返回你自定义的错误消息,不用改动错误处理代码。

方案2:捕获错误时直接读取异常属性

如果不想修改异常类,就在catchError里判断错误类型,直接提取属性拼接消息:

}).catchError((error) {
  setState(() {
    _loader = false;
    if (error is CustomException) {
      _errorMessage = '${error.message}: ${error.subMessage}';
      // 可选:加上code信息
      if (error.codeNumber != null) {
        _errorMessage += ' (错误码: ${error.codeNumber})';
      }
      if (error.codeString != null) {
        _errorMessage += ' (错误标识: ${error.codeString})';
      }
    } else {
      _errorMessage = error.toString();
    }
  });
});

建议

优先选方案1,因为所有地方捕获这个异常时,调用toString()都能得到统一的友好提示,不用重复编写处理逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:55:21