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
相关产品推荐
相关产品推荐

