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 c4b9dafcb..8e7d0f64a 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 @@ -141,42 +141,40 @@ public class CzgControllerAdvice { } @ResponseBody - @ExceptionHandler(Exception.class) + @ExceptionHandler(value = 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(); + if (rootCause instanceof CzgException czgException) { + return CzgResult.failure(czgException.getCode(), czgException.getMessage()); + } + if (rootCause instanceof OrderValidateException orderValidateException) { + return CzgResult.failure(orderValidateException.getCode(), orderValidateException.getMessage()); + } + if (rootCause instanceof PaySuccessException) { + return CzgResult.failure(701, "订单已过期,请重新下单"); + } + if (rootCause instanceof OrderCancelException) { + return CzgResult.success("支付成功"); + } } - return rootCause; + // 处理自定义异常 + if (rootCause instanceof CzgException czgException) { + return CzgResult.failure(czgException.getCode(), czgException.getMessage()); + } + if (rootCause instanceof OrderValidateException orderValidateException) { + return CzgResult.failure(orderValidateException.getCode(), orderValidateException.getMessage()); + } + if (rootCause instanceof OrderCancelException) { + return CzgResult.failure(701, "订单已过期,请重新下单"); + } + if (rootCause instanceof PaySuccessException) { + return CzgResult.success("支付成功"); + } + setErrorLog(ex); + return CzgResult.failure(CzgRespCode.SYSTEM_ERROR.getCode(), ex.getMessage()); } private void setErrorLog(Exception ex) {