异常打印3

This commit is contained in:
wangw 2025-11-12 11:20:39 +08:00
parent 3cb39035ed
commit f37744b2c6
1 changed files with 39 additions and 19 deletions

View File

@ -140,27 +140,47 @@ public class CzgControllerAdvice {
return CzgResult.failure(CzgRespCode.RECORD_EXISTED); return CzgResult.failure(CzgRespCode.RECORD_EXISTED);
} }
// @ResponseBody @ResponseBody
// @ExceptionHandler(value = Exception.class) @ExceptionHandler(Exception.class)
// @ResponseStatus(HttpStatus.OK) @ResponseStatus(HttpStatus.OK)
// public CzgResult<Object> errorHandler(Exception ex) { public CzgResult<Object> errorHandler(Exception ex) {
// Throwable rootCause = ex; // 1. 提取根异常简化循环逻辑避免冗余判断
// while (rootCause.getCause() != null) { Throwable rootCause = getRootCause(ex);
// rootCause = rootCause.getCause();
// if (rootCause instanceof CzgException) { // 2. 处理自定义异常使用策略模式/条件分支优化增加注释说明
// break; if (rootCause instanceof CzgException czgException) {
// } // 业务自定义异常返回具体错误码和消息
// } return CzgResult.failure(czgException.getCode(), czgException.getMessage());
// // 处理自定义异常 } else if (rootCause instanceof OrderValidateException validateException) {
// if (rootCause instanceof CzgException czgException) { // 订单验证异常返回验证错误信息
// return CzgResult.failure(czgException.getCode(), czgException.getMessage()); return CzgResult.failure(validateException.getCode(), validateException.getMessage());
// } } else if (rootCause instanceof OrderCancelException) {
// setErrorLog(ex); // 订单取消/过期异常固定错误码和提示
// return CzgResult.failure(CzgRespCode.SYSTEM_ERROR.getCode(), ex.getMessage()); 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) { private void setErrorLog(Exception ex) {
// log.error(ex.getMessage()); log.error(ex.getMessage());
log.error("错误", ex); log.error("错误", ex);
} }
} }