Springboot Restful接口及异常统一返回值实现

为什么要统一返回值

两点:
1 为了制定规范提高工作效率(效率)
2 统一异常处理给用户一个正确的提示(易用)

实现原理

使用@ControllerAdvice注解,该注解是Springmvc controller增强器。

统一接口的返回值实现

返回钱处理流程

使用@ControllerAdvice注解,实现ResponseBodyAdvice的beforeBodyWrite方法,用于对@ResponseBody返回值增加处理。

统一异常的返回值实现

使用@ControllerAdvice注解,自定义异常处理类,当被@ExceptionHandler注解的方法发生异常会处理定义的异常,然后分发到具体的处理方法。

实现方法

统一接口的返回值代码实现

统一返回数据定义(RestReturn.java)

package com.springboot.action.saas.common.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.time.Instant;

/**
 * 接口返回统一数据结构
 */
@Data
public class RestReturn {
    //是否成功标志
    private boolean success;
    //code错误码
    private Integer code;
    //外带数据信息
    private Object data;
    //前端进行页面展示的信息
    private Object message;
    //返回时间戳
    private Long currentTime;
    /**
     *构造函数(无参数)
     */
    public RestReturn() {
        //毫秒
        this.currentTime = Instant.now().toEpochMilli();
    }
    /**
     *构造函数(有参数)
     */
    public RestReturn(boolean success, Integer code, Object data, Object message) {
        this.success = success;
        this.code = code;
        this.data = data;
        this.message = message;
        //毫秒
        this.currentTime = Instant.now().toEpochMilli();
    }
    @Override
    public String toString() {
        return "RestReturn{" +
                "success=" + success +
                ",code='" + code + '\'' +
                ",data=" + data +
                ",message=" + message +
                ",currentTime=" + currentTime +
                '}';
    }

    public RestReturn success(Object data, Object message) {
        this.success = true;
        this.code = 0;
        this.data = data;
        this.message = message;

        return this;
    }

    public RestReturn error(Integer code, Object data, Object message) {
        this.success = false;
        this.code = code;
        this.data = data;
        this.message = message;

        return this;
    }

    public boolean isRestReturnJson(String data) {
        //临时实现先判定下字符串的格式和字段
        try {
            /**
             * ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
             */
            ObjectMapper mapper = new ObjectMapper();
            RestReturn dataRestReturn = mapper.readValue(data, RestReturn.class);
            //比较两个类的字段,如果一致返回为真,不一致返回为假
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

实现ResponseBodyAdvice接口,重写beforeBodyWrite,对返回的body做规范化返回值(RestReturnWrapper.java)

package com.springboot.action.saas.common.controller;

import org.springframework.core.MethodParameter;
import org.springframework.core.io.Resource;
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.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class RestReturnWrapper implements ResponseBodyAdvice<Object> {
    /**
     * 判定哪些请求要执行beforeBodyWrite,返回true执行,返回false不执行
     * */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        //获取当前处理请求的controller的方法
        //String methodName = methodParameter.getMethod().getName();
        // 拦/不拦截处理返回值的方法,如登录
        //String method = "login";
        //这里可以加入很多判定,如果在白名单的List里面,是否拦截
        return true;
    }


    /**
     * 返回前对body,request,response等请求做处理
     *
     * @param body
     * @param methodParameter
     * @param mediaType
     * @param httpMessageConverter
     * @param serverHttpRequest
     * @param serverHttpResponse
     *
     * @return
     * */
    @Override
    public Object beforeBodyWrite(Object body,
                    MethodParameter methodParameter,
                    MediaType mediaType,
                    Class<? extends HttpMessageConverter<?>> httpMessageConverter,
                    ServerHttpRequest serverHttpRequest,
                    ServerHttpResponse serverHttpResponse) {
        //具体返回值处理
        //情况1 如果返回的body为null
        if(body == null){
            if (mediaType == MediaType.APPLICATION_JSON) {
                //返回是json个格式类型,无body内容
                RestReturn restReturn = new RestReturn();
                return restReturn.success("", "");
            } else {
                return null;
            }
        } else {
            //情况2 文件上传下载,不需要改动,直接返回
            if (body instanceof Resource) {
                return body;
            } else if (body instanceof String) {
                // 返回的是 String,
                RestReturn restReturn = new RestReturn();
                try {
                    if (restReturn.isRestReturnJson((String) body)) {
                        // 情况3 已经是RestReturn格式的json 字符串不做统一格式封装
                        return body;
                    } else {
                        //情况4 普通的返回,需要统一格式,把数据赋值回去即可。
                        return restReturn.success(body, "");
                    }
                } catch (Exception e) {
                    // 因为 API返回值为String,理论上不会走到这个分支。
                    return restReturn.error(10000, body, e.getMessage());
                }
            } else {
                //返回的是非字符串格式,实际上很多时候用都是是在应用程返回的对象居多
                if(body instanceof RestReturn){
                    //情况5 如果已经封装成RestReturn,直接return
                    return body;
                }else{
                    //情况6 非字符串非统一格式的返回,需要统一格式
                    //需要判定是否是抛出的异常返回(统一到错误输出)
                    RestReturn restReturn = new RestReturn();
                    return restReturn.success(body, "");
                }
            }
        }
    }
}

统一异常的返回值实现

返回值统一处理后,发生异常的时候,异常的信息会全出现在body中,这个不是最终想要的结果。

定义统一的异常返回值和提示(RestReturnEnum.java)

package com.springboot.action.saas.common.controller;

/**
 * 接口返回状态和错误提示
 */
public enum RestReturnEnum {
    SUCCESS(200, "成功"),
    FAIL(-1, "失败"),
    BAD_REQUEST(400, "错误请求"),
    FORBIDDEN(403, "禁止访问"),
    NOT_FOUND(404, "未找到"),
    EXCEPTION(500, "系统异常");

    //code错误码
    private Integer code;
    //前端进行页面展示的信息
    private String message;

    private RestReturnEnum(Integer code, String message){
        this.code = code;
        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
}

定义自定义异常处理类(EntityNotFoundException.java)

样例定义个获取数据库对应的数据为空的异常

package com.springboot.action.saas.common.exception;

import org.springframework.util.StringUtils;

public class EntityNotFoundException extends RuntimeException {

    public EntityNotFoundException(Class clazz,
                                   String key,
                                   String value) {
        super(EntityNotFoundException.generateMessage(
                clazz.getSimpleName(),
                key,
                value));
    }
    //转化为字符串,类的名字和k-v结构可变参数
    private static String generateMessage(String entity,
                                          String key,
                                          String value) {
        return StringUtils.capitalize(entity) +
                " 未找到 " +
                key +
                " : " +
                value;
    }
}

定义全局异常处理Advice(GlobalExceptionAdvice.java)

指定发生的异常由那些异常处理类处理。

package com.springboot.action.saas.common.exception;

import com.springboot.action.saas.common.controller.RestReturn;
import com.springboot.action.saas.common.controller.RestReturnEnum;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionAdvice {
    /**
     * 处理所有不可知的异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public RestReturn defaultException(HttpServletRequest request, Exception e){
        //输出堆栈信息到控制台,以后记录到日志
        e.printStackTrace();
        return new RestReturn(
                false,
                RestReturnEnum.EXCEPTION.getCode(),
                "",
                RestReturnEnum.EXCEPTION.getMessage()
        );
    }

    /**
     * 处理 接口无权访问异常AccessDeniedException FORBIDDEN(403, "Forbidden"),
     * @param e
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public RestReturn accessDeniedException(AccessDeniedException e){
        //输出堆栈信息到控制台,以后记录到日志
        e.printStackTrace();
        return new RestReturn(
                false,
                RestReturnEnum.FORBIDDEN.getCode(),
                "",
                RestReturnEnum.FORBIDDEN.getMessage()
        );
    }

    /**
     * 处理bad请求异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public RestReturn badRequestException(RuntimeException e) {
        e.printStackTrace();
        return new RestReturn(
                false,
                RestReturnEnum.BAD_REQUEST.getCode(),
                "",
                RestReturnEnum.BAD_REQUEST.getMessage()
        );
    }

    /**
     * 处理 EntityNotFound 数据库数据未找到
     * @param e
     * @return
     */
    @ExceptionHandler(value = EntityNotFoundException.class)
    @ResponseBody
    public RestReturn entityNotFoundException(EntityNotFoundException e) {
        // 打印堆栈信息
        e.printStackTrace();
        return new RestReturn(
                false,
                RestReturnEnum.NOT_FOUND.getCode(),
                "",
                RestReturnEnum.NOT_FOUND.getMessage()
        );
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容