Spring Boot unified data return format

Foreword:

        When we start the project, we must agree with the front-end on the relevant structure of the interface. It is very important to agree on the format of the data returned by the interface, which involves whether the data can be transmitted correctly. Our back-end returns a unified data format, which can be used by the front-end and the front-end. Save a lot of trouble in communication and project development

Quick Start:

 Response notification class - Unified data return format (the interface returns the response correctly)

        The unified data return format uses @ControllerAdvice and ResponseBodyAdvice Implement @ControllerAdvice representationResponse notification class Add class ResponseAdvice, implement ResponseBodyAdvice interface, and add @ControllerAdvice annotation on the class< /span>

@ControllerAdvice
@Slf4j
public class ResponseAdvice implements ResponseBodyAdvice {
    private ObjectMapper objectMapper=new ObjectMapper();
    // supports 方法开启 beforeBodyWrite 方法
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    // beforeBodyWrite ⽅法:就是对响应进⾏具体操作处理
    // body 代表接口原本要返回的数据
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        log.info("进行统一数据返回格式body:{}",body);
        //当接口原本要返回的数据类型就是 Result 时,就不继续封装成 Result 对象了
        if(body instanceof Result){
            return body;
        }

        //当接口原本要返回的数据类型是 String 时,要进行特殊处理,要把返回的 Result 对象解析成 json 格式的字符串进行返回
        if(body instanceof String){
            return objectMapper.writeValueAsString(Result.success(body));
        }

        return Result.success(body);
    }
}

         Adding the @ControllerAdvice annotation can hand over the ResponseAdvice object to Spring's IoC container for management. can act on the global interface. , @ The ControllerAdvice annotation does not belong to the five major annotations. Why can it play the same role? Because the @ControllerAdvice annotation is implemented based on the @Component annotation

        Rewrite the supports method and beforeBodyWrite method in the ResponseBodyAdvice interface

        supports method : Determine whether to execute the beforeBodyWrite method. true means execution, false means not execution.

         beforeBodyWrite method : Specific processing details of unified interface data return format

        The parameter body in the beforeBodyWrite method is the data content originally returned by the interface. We need to re-encapsulate this data content into a Result type object and then return it to the front end, so that the data received by the front end is in the Result type format.

       There are two special situations when unifying the interface data return format:

        (1). The type to be returned by the interface is already the specified Result type. At this time, there is no need to encapsulate it, just return it directly.

        (2).The type returned by the interface is String type. At this time, special processing is required, and the String type data is encapsulated into After the Result type, the Result type object needs to be parsed into a json format string before it can be returned, otherwise an error will be reported. This special situation is a source code problem of Spring Boot

        It should be noted that Response Notification Class  is unified in the data format when the interface correctly returns the response. To unify the exception return format, you need to see the following Introduced Exception Handler

Exception handler - Uniform exception return format:

        The unified exception return format is implemented using @ControllerAdvice + @ExceptionHandler. @ControllerAdvice represents the controller notification class, and @ExceptionHandler is the exception handler. The combination of the two represents a notification to be executed when an exception occurs. That is, executing a method event

//异常处理器
//统一异常返回格式
@ControllerAdvice
//加上 @ResponseBody 注解 Spring 才知道返回的是数据,要不然就会去寻找对应 URL 的网页
@ResponseBody
public class ErrorAdvice {

    //异常都是继承于 Exception 类的,所以使用 Exception 就可以捕获到 Exception 及其所有子类异常
    //当然也可以更具体的捕获异常,进行处理
    @ExceptionHandler
    public Object hander(Exception e){
        return Result.fail(e.getMessage());
    }

    //专门捕获空指针异常进行处理
    @ExceptionHandler
    public Object hander(NullPointerException e){
        return Result.fail("发⽣NullPointerException:"+e.getMessage());
    }

    //专门捕获运算异常进行处理
    @ExceptionHandler
    public Object hander(ArithmeticException e){
        return Result.fail("发⽣ArithmeticException:"+e.getMessage());
    }


}

         Add @ControlLeradvice annotation to give the object of ErRoradvice to the Spring IOC container for managing it. The ControllerAdvice annotation does not belong to the five major annotations. Why can it play the same role? Because the @ControllerAdvice annotation is implemented based on the @Component annotation

        Add @ResponseBody The annotation is to explain to Spring that the data is returned instead of the page. If the annotation is not added, Spring will return If you use the data as a URL to find the corresponding page, a 404 error will be reported

        The parameters in the custom method handler represent the exceptions to be caught. When the corresponding exception or subclass exception occurs in the interface, it will be returned in the set format. The above code, when the corresponding exception is captured, is encapsulated into Result object is returned, unifying the format of exception return.

        

Guess you like

Origin blog.csdn.net/q322359/article/details/134732319