spring boot 全局异常处理捕获分页查询异常,核心在于利用 @controlleradvice 配合 @exceptionhandler 拦截 org.springframework.data.domain.pageableexecutionexception 或底层数据库抛出的 badsqlgrammarexception、paginationexception。具体做法是定义一个全局异常处理器类,在其中编写针对这些特定异常的处理方法,返回统一的 json 响应对象,从而避免应用崩溃并向前端返回清晰的错误信息。

如何配置全局异常处理器来拦截分页相关异常
要实现对分页查询异常的捕获,必须创建一个被 @RestControllerAdvice 或 @ControllerAdvice 注解修饰的类。在这个类中,使用 @ExceptionHandler 注解指定需要处理的异常类型。对于分页查询,常见的异常来源包括 MyBatis-Plus 的分页插件异常、Hibernate 的 SQL 语法错误或 Spring Data JPA 的参数绑定异常。通过将这些异常类作为参数注入到处理方法中,可以精准定位问题。

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<map object>> handleGeneralException(Exception e) {
Map<string object> body = new HashMap();
body.put("status", 500);
body.put("message", "服务器内部错误: " + e.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body);
}
@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<map object>> handleDataIntegrityException(DataIntegrityViolationException e) {
Map<string object> body = new HashMap();
body.put("status", 400);
body.put("message", "数据完整性违反,请检查输入参数");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
}
}</string></map></string></map>
上述代码展示了一个基础的全局异常处理器。它首先捕获所有未处理的 Exception,确保任何意外错误都能被兜底处理。其次,它专门捕获 DataIntegrityViolationException,这在分页查询中可能因约束冲突触发。开发者需根据实际使用的持久层框架(如 JPA 或 MyBatis)添加对应的异常类,例如 org.hibernate.exception.ConstraintViolationException 或 com.baomidou.mybatisplus.core.exceptions.MybatisPlusException。运行此配置后,当分页查询发生异常时,系统将不再抛出堆栈跟踪,而是返回结构化的 JSON 数据。
分页查询中哪些具体异常需要单独处理
在分页查询场景下,并非所有异常都适合统一处理。需要单独关注的异常主要包括 SQL 语法错误、参数类型不匹配以及分页插件特有的异常。例如,MyBatis-Plus 在使用 Page 对象时,如果 SQL 语句中存在不支持的函数或子查询,可能会抛出 InvalidParameterException。而 Hibernate 在生成分页 SQL 时,若方言配置错误,会抛出 QuerySyntaxException。区分这些异常有助于提供更精确的错误提示。

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@GetMapping("/users")
public Page<user> getUsers(@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int size) {
QueryWrapper<user> queryWrapper = new QueryWrapper();
// 假设 User 实体有 name 字段
queryWrapper.like("name", "test");
return userService.page(new Page(page, size), queryWrapper);
}
}</user></user>
以上代码是一个典型的分页查询接口实现。它接收页码和每页大小作为参数,并使用 QueryWrapper 构建查询条件。当用户传入非法的 page 或 size 值(如负数或零)时,MyBatis-Plus 可能会抛出 IllegalArgumentException。此外,如果数据库表中不存在 name 列,执行时将抛出 SQLSyntaxErrorException。为了完善异常处理,应在 GlobalExceptionHandler 中添加对 IllegalArgumentException 的处理,以验证分页参数的合法性。同时,对于 SQL 语法错误,可捕获 SQLException 的子类,提取具体的 SQL 错误码,以便前端进行针对性提示。这种细粒度的异常处理策略,能显著提升系统的健壮性和用户体验。
如何处理分页查询中的空结果集与默认行为
分页查询中,当查询结果为空时,系统通常不会抛出异常,而是返回一个空的 Page 对象。此时,Page 的 getRecords() 方法将返回空列表,getTotal() 返回 0。开发者需明确这一默认行为,并在前端做好空状态展示。若业务要求在某些条件下(如参数缺失)直接返回错误而非空结果,则需在 Service 层增加前置校验逻辑,或在 Controller 层通过自定义异常抛出。例如,若要求 size 必须大于 0,可在参数绑定阶段或使用 @Validated 注解进行校验,失败时抛出 MethodArgumentNotValidException,由全局异常处理器统一响应。











