spring boot 全局异常处理无法直接捕获业务逻辑中的偏移量异常,因为这类异常通常不是由框架自动抛出的运行时错误。正确的做法是在 service 层或 controller 层显式检查参数合法性,当发现偏移量(offset)为负数或超出数据范围时,手动抛出如 illegalargumentexception 或自定义的 offsetoutofboundsexception,然后利用 @controlleradvice 配合 @exceptionhandler 统一拦截这些异常并返回标准化的 json 响应。

如何定义并抛出偏移量异常
在业务代码中,你需要在访问列表或分页数据前验证 offset 和 limit 参数。如果 offset 小于 0,或者计算出的结束位置超过了集合的实际大小,就应当立即中断流程并抛出异常。这确保了无效请求不会进入后续的数据处理环节。

import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DataService {
public List<String> getData(int offset, int limit) {
if (offset < 0) {
throw new IllegalArgumentException("Offset cannot be negative");
}
// 模拟数据源
List<String> allData = List.of("A", "B", "C", "D", "E");
if (offset >= allData.size()) {
return List.of(); // 超出范围返回空列表,也可选择抛出自定义异常
}
int end = Math.min(offset + limit, allData.size());
return allData.subList(offset, end);
}
}上述代码展示了在 DataService 中如何处理边界情况。当 offset 为负数时抛出 IllegalArgumentException,这是 Spring MVC 默认能识别的参数错误类型。当 offset 超出数据总量时,代码选择了返回空列表而非抛出异常,这是一种常见的业务策略,具体取决于需求。若需强制报错,可替换为自定义异常。
如何在全局处理器中捕获并响应
创建配置类实现 @ControllerAdvice,并在其中定义针对特定异常的处理方法。使用 @ExceptionHandler 注解指定要捕获的异常类型,例如 IllegalArgumentException 或你自定义的偏移量异常。处理方法应返回 ResponseEntity,以便控制 HTTP 状态码和响应体结构。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Invalid parameter: " + ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneral(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An unexpected error occurred");
}
}该全局异常处理器首先尝试捕获 IllegalArgumentException,这涵盖了偏移量为负的情况。对于其他未预期的异常,它提供了一个通用的兜底处理。通过这种方式,前端可以接收到明确的错误信息,而不是默认的 500 错误或堆栈跟踪页面。
当偏移量导致子列表越界时会发生什么
如果在调用 List.subList() 时,传入的 fromIndex 或 toIndex 超出了列表的有效索引范围,Java 会抛出 IndexOutOfBoundsException。这是一个运行时异常,如果不被显式捕获,它将沿着调用栈向上传播,最终被 Spring Boot 的全局异常处理器(如果配置了 Exception.class 的捕获器)或默认的错误映射机制处理。


















