代码解释1

提交1
lkw2731938298 2 weeks ago
parent 2616fc71f5
commit 4a56c21407

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