SpringBoot 统一返回数据结构与异常处理

2019-04-08  本文已影响0人  土豆泥加冰谢谢

在前后端交互时,我们一般会统一接口的数据结构。

public class Result<T> {
    private Integer code;
    private String message;
    private T data;
}

code即定义接口的返回码,例如200对应请求成功
message即接口的返回信息,比如如果请求异常,message内就存放的异常信息
data则为具体需要的数据,这里使用T泛型,兼容所有返回类型

统一异常处理

我们首先构造一个Enum类来统一管理所有的异常分类:


public enum ExceptionEnum {
    SUCCSEE(200,"请求成功"),
    UNKNOW(-1000,"未知错误");

    private Integer code;
    private String message;
    ExceptionEnum(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;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

因为我们的统一返回结果Result是有code以及message的,而默认的Exception没有code字段,所以接着构造一个异常基类来封装(注意继承RuntimeException而非Exception):

public class DemoException extends RuntimeException {

    public DemoException(ExceptionEnum exceptionEnum) {
        super(exceptionEnum.getMessage());
        this.code = exceptionEnum.getCode();
    }

    private Integer code;

    public Integer getCode() {
        return code;
    }

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

最后使用SpringBoot的@ControllerAdvice注解结合@ExceptionHandler注解对异常进行统一处理:

@ControllerAdvice
public class ExceptionHandle {

    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public Result handle(Exception exception){
        Result result=new Result();
        if (exception instanceof DemoException){
            result.setCode(((DemoException) exception).getCode());
        }else {
            DemoException demoException=new DemoException(ExceptionEnum.UNKNOW);
            result.setCode(demoException.getCode());
        }
        result.setMessage(exception.getMessage());
        return result;
    }
}
上一篇下一篇

猜你喜欢

热点阅读