Springboot统一返回处理

Springboot统一返回处理

SpringBoot 统一返回格式处理

SpringBoot 统一异常返回处理

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class) //表示让Spring捕获到所有抛出的SignException异常,并交由这个被注解的方法处理。
    @ResponseStatus(HttpStatus.BAD_REQUEST)  //表示设置状态码。
    public String handleException(){
        return "Exception Deal!";
    }
}

SpringBoot 统一正常返回处理

在SpringBoot中我们可以通过@RestControllerAdvice注解与 ResponseBodyAdvice<T> 接口实现Rest返回统一格式

首先规定一个返回格式的类

import com.fasterxml.jackson.annotation.JsonInclude;
import java.io.Serializable;

//  json序列化时省略空字段
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> implements Serializable {
    private Integer code;
    private String msg;
    private T data;
    public Result(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    //省略 getter setter
}

然后创建GlobalResultHandler类实现ResponseBodyAdvice<Object>接口

import com.orange.common.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class GlobalResultHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     * 在Body返回之前验证返回的类型是否是统一返回类型,
     * 若是则正常返回
     * 不是则对这个类进行包装
    **/
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof Result){
            return body;
        }
        return new Result(200,"success",body);
    }
}