pull/2/head
lkw2731938298 3 weeks ago
parent 1ced6e56f0
commit ece6b6031d

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

Loading…
Cancel
Save