|
|
|
@ -1,24 +1,33 @@
|
|
|
|
|
// 包声明:定义当前类所在的包路径
|
|
|
|
|
package com.shanzhu.market.common.advice;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import com.shanzhu.market.common.constants.HttpStatus;
|
|
|
|
|
import com.shanzhu.market.common.exception.BusinessException;
|
|
|
|
|
import com.shanzhu.market.common.web.response.JsonResult;
|
|
|
|
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
|
|
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
|
|
|
|
// 导入依赖的类库
|
|
|
|
|
import com.shanzhu.market.common.constants.HttpStatus; // HTTP状态码常量
|
|
|
|
|
import com.shanzhu.market.common.exception.BusinessException; // 自定义业务异常
|
|
|
|
|
import com.shanzhu.market.common.web.response.JsonResult; // 统一响应格式工具类
|
|
|
|
|
import org.springframework.web.bind.annotation.ExceptionHandler; // Spring异常处理注解
|
|
|
|
|
import org.springframework.web.bind.annotation.RestControllerAdvice; // Spring控制器增强注解
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 统一异常处理类的基类
|
|
|
|
|
* 统一异常处理类的基类(类注释说明核心功能)
|
|
|
|
|
*/
|
|
|
|
|
@RestControllerAdvice
|
|
|
|
|
@RestControllerAdvice // 标识该类为全局REST控制器异常处理器
|
|
|
|
|
public class ExceptionControllerAdvice {
|
|
|
|
|
|
|
|
|
|
// 处理所有RuntimeException及其子类异常
|
|
|
|
|
@ExceptionHandler(RuntimeException.class)
|
|
|
|
|
public JsonResult<?> commonExceptionHandler(RuntimeException ex){
|
|
|
|
|
ex.printStackTrace();
|
|
|
|
|
return JsonResult.error(HttpStatus.CODE_BUSINESS_ERROR,ex.getMessage());
|
|
|
|
|
ex.printStackTrace(); // 打印异常堆栈跟踪(生产环境建议替换为日志记录)
|
|
|
|
|
return JsonResult.error( // 返回标准错误响应
|
|
|
|
|
HttpStatus.CODE_BUSINESS_ERROR, // 使用预定义的业务错误码
|
|
|
|
|
ex.getMessage()); // 携带异常消息
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 专门处理自定义业务异常
|
|
|
|
|
@ExceptionHandler(BusinessException.class)
|
|
|
|
|
public JsonResult<?> businessHanler(BusinessException ex){
|
|
|
|
|
return JsonResult.error(HttpStatus.CODE_BUSINESS_ERROR,ex.getMessage());
|
|
|
|
|
return JsonResult.error( // 返回标准错误响应
|
|
|
|
|
HttpStatus.CODE_BUSINESS_ERROR, // 使用相同的业务错误码保持一致性
|
|
|
|
|
ex.getMessage()); // 携带业务异常消息
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|