From f37744b2c6b6ca3bac9e68f452819498f614c07d Mon Sep 17 00:00:00 2001 From: wangw <1594593906@qq.com> Date: Wed, 12 Nov 2025 11:20:39 +0800 Subject: [PATCH] =?UTF-8?q?=E5=BC=82=E5=B8=B8=E6=89=93=E5=8D=B03?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../czg/exception/CzgControllerAdvice.java | 58 +++++++++++++------ 1 file changed, 39 insertions(+), 19 deletions(-) diff --git a/cash-common/cash-common-api-config/src/main/java/com/czg/exception/CzgControllerAdvice.java b/cash-common/cash-common-api-config/src/main/java/com/czg/exception/CzgControllerAdvice.java index 66ba5653..c4b9dafc 100644 --- a/cash-common/cash-common-api-config/src/main/java/com/czg/exception/CzgControllerAdvice.java +++ b/cash-common/cash-common-api-config/src/main/java/com/czg/exception/CzgControllerAdvice.java @@ -140,27 +140,47 @@ public class CzgControllerAdvice { return CzgResult.failure(CzgRespCode.RECORD_EXISTED); } -// @ResponseBody -// @ExceptionHandler(value = Exception.class) -// @ResponseStatus(HttpStatus.OK) -// public CzgResult errorHandler(Exception ex) { -// Throwable rootCause = ex; -// while (rootCause.getCause() != null) { -// rootCause = rootCause.getCause(); -// if (rootCause instanceof CzgException) { -// break; -// } -// } -// // 处理自定义异常 -// if (rootCause instanceof CzgException czgException) { -// return CzgResult.failure(czgException.getCode(), czgException.getMessage()); -// } -// setErrorLog(ex); -// return CzgResult.failure(CzgRespCode.SYSTEM_ERROR.getCode(), ex.getMessage()); -// } + @ResponseBody + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.OK) + public CzgResult errorHandler(Exception ex) { + // 1. 提取根异常(简化循环逻辑,避免冗余判断) + Throwable rootCause = getRootCause(ex); + + // 2. 处理自定义异常(使用策略模式/条件分支优化,增加注释说明) + if (rootCause instanceof CzgException czgException) { + // 业务自定义异常:返回具体错误码和消息 + return CzgResult.failure(czgException.getCode(), czgException.getMessage()); + } else if (rootCause instanceof OrderValidateException validateException) { + // 订单验证异常:返回验证错误信息 + return CzgResult.failure(validateException.getCode(), validateException.getMessage()); + } else if (rootCause instanceof OrderCancelException) { + // 订单取消/过期异常:固定错误码和提示 + return CzgResult.failure(701, "订单已过期,请重新下单"); + } else if (rootCause instanceof PaySuccessException) { + // 支付成功异常(特殊场景:异常中包含成功状态) + return CzgResult.success("支付成功"); + } + + // 3. 处理未捕获的异常(系统异常,隐藏敏感信息) + log.error("系统未处理异常", ex); + return CzgResult.failure(CzgRespCode.SYSTEM_ERROR.getCode(), "系统繁忙,请稍后再试"); + } + + /** + * 提取异常链中的根异常(最底层的原始异常) + */ + private Throwable getRootCause(Throwable ex) { + Throwable rootCause = ex; + // 循环获取根异常,直到没有更深层的原因 + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + return rootCause; + } private void setErrorLog(Exception ex) { -// log.error(ex.getMessage()); + log.error(ex.getMessage()); log.error("错误", ex); } }