From ece6b6031d2e4c45abdbfd2d3b96c163e683388f Mon Sep 17 00:00:00 2001 From: lkw2731938298 <133633447+lkw2731938298@users.noreply.github.com> Date: Wed, 23 Apr 2025 17:49:18 +0800 Subject: [PATCH] =?UTF-8?q?20=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../advice/ExceptionControllerAdvice.java | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/superMarket-backend/src/main/java/com/shanzhu/market/common/advice/ExceptionControllerAdvice.java b/superMarket-backend/src/main/java/com/shanzhu/market/common/advice/ExceptionControllerAdvice.java index 6752740..4b31f09 100644 --- a/superMarket-backend/src/main/java/com/shanzhu/market/common/advice/ExceptionControllerAdvice.java +++ b/superMarket-backend/src/main/java/com/shanzhu/market/common/advice/ExceptionControllerAdvice.java @@ -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()); // 携带业务异常消息 } }