异常打印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);
}
// @ResponseBody
// @ExceptionHandler(value = Exception.class)
// @ResponseStatus(HttpStatus.OK)
// public CzgResult<Object> 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<Object> 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);
}
}