异常打印3
This commit is contained in:
parent
3cb39035ed
commit
f37744b2c6
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue