Spring Boot统一功能处理

1. 统一数据返回格式

统一数据返回格式,就是对返回的数据做一个统一的处理:

java 复制代码
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    ObjectMapper mapper;
    //判断是否要执行beforeBodyWrite方法
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {

        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof Result) {
            return body;
        }

        if(body instanceof String) {
            return mapper.writeValueAsString(Result.success(body));
        }
        return Result.success(body);
    }
}

创建一个类实现RespinseBodyAdvice接口

@ControllerAdvice 表示控制器通知类

supports方法用于判断当前的响应是否要做处理,true表示需要,则会执行beforeBodyWrite方法来处理,false则不会执行。

注意:如果返回的结果是String类型的话,需要把处理后的body转为String类型,否则会报错。

2. 统一异常处理

如果发生异常时,我们不希望把它展示给用户可以使用统一异常处理,自定义发生异常时展示的内容:

java 复制代码
@Slf4j
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {
    @ExceptionHandler
    public Result HandleException(Exception e) {
        log.error("发生异常:", e);
        return Result.fail("内部错误");
    }
}

这里可以写多个HandleException方法来处理不同的异常,处理异常时会按照异常的深度顺序对应来处理。

注意:添加了统一异常处理后,发生的异常都会被处理掉,也就不会出现异常信息,需要我们自己用日志打印。

相关推荐
一 乐1 小时前
动漫书销售商城|基于springboot + vue动漫书销售商城(源码+数据库+文档)
java·数据库·vue.js·spring boot·毕业设计
卓怡学长1 小时前
w214基于jsp知道特产网
java·intellij-idea
步行cgn1 小时前
Spring 注解使用详解
java·spring
一条小小yu1 小时前
Spring IoC的理解
java·后端·spring
落魄实习生2 小时前
Agent Scope Java 2.x 系列【7】工具使用
java·开发语言·ai
旺仔学长 哈哈2 小时前
springboot钓鱼爱好者交流平台APP设计与实现
java·spring boot·mysql·充电桩管理系统
茉莉玫瑰花茶2 小时前
GO [ 方法 ]
开发语言·后端·golang
Wx-bishekaifayuan2 小时前
django个性化旅游路线推荐平台49005-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
Eric_见嘉3 小时前
在职前端 Skill 和 MCP 分享
前端·后端·agent