SpringBoot 统一数据返回与异常处理详解
在开发过程中,前后端交互的数据格式往往需要标准化。通过 SpringBoot 提供的扩展点,我们可以轻松实现统一的响应封装和全局异常捕获,减少重复代码并提升系统健壮性。
统一数据返回格式
快速入门
利用 @ControllerAdvice 配合 ResponseBodyAdvice 接口是实现统一响应的经典方案。前者用于定义通知类,后者则负责拦截控制器方法的返回值。
package com.hbu.book.responseAdvice;
import org.jspecify.annotations.Nullable;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
public class ResponseAdvice implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return false;
}
@Override
public @Nullable Object beforeBodyWrite(@Nullable Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response) {
return null;
}
}
supports 方法决定了是否执行后续的处理逻辑。默认返回 false 表示不生效,我们需要将其改为 true 以启用统一封装。
未配置前,接口直接返回原始数据:







