Spring Boot - 5

in JAVA with 0 comment

统一异常处理

统一返回数据的格式

创建一个Result类,用来作为返回值的类型

public class Result<T> {

    //错误码
    private Integer code;

    //提示信息
    private String msg;

    //数据
    private T data;

    public Integer getCode() {
        return code;
    }

    public Result() {
    }

    public Result(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

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

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}

ResultUtil,工具类,用来简化代码

import cn.medemede.springbootdemo1.domain.Result;

public class ResultUtil {

    public static Result success(Object o){
        Result result=new Result();
        result.setCode(0);
        result.setMsg("success");
        result.setData(o);

        return result;
    }

    public static Result error(Integer code,String msg){
        Result result=new Result();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }
}

创建统一异常处理handle

此类会拦截所有系统抛出的异常,并封装成Result的格式

import cn.medemede.springbootdemo1.domain.Result;
import cn.medemede.springbootdemo1.exception.GirlException;
import cn.medemede.springbootdemo1.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ExceptionHandle {

    private static Logger logger= LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e){

        if(e instanceof GirlException){
            return ResultUtil.error(((GirlException) e).getCode(),e.getMessage());
        }else {
            logger.error("【系统异常】:{}", e);
            return ResultUtil.error(-1, "系统错误");
        }
    }

}

创建自定义异常


import cn.medemede.springbootdemo1.enums.ResultEnum;

public class GirlException extends RuntimeException {

    private Integer code;

    public GirlException(Integer code,String message){
        super(message);
        this.code=code;
    }

    public GirlException(ResultEnum resultEnum){
        super(resultEnum.getMessage());
        this.code=resultEnum.getCode();
    }

    public Integer getCode() {
        return code;
    }

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

}

创建异常枚举类

为了方便异常的管理和使用,用一个枚举类来定义所有异常

public enum ResultEnum {
    SUCCESS(0,"success"),
    UNKONW_ERROR(-1,"UNKONW ERROR"),
    PRIMARY_SCHOOL(100,"PRIMARY SCHOOL"),
    HIGH_SCHOOL(101,"HIGH SCHOOL"),
    ;

    private Integer code;
    private String message;

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

    public Integer getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

单元测试

使用idea进行单元测试

使用idea可以发很难改变的可以方便的进行单元测试 只需要在需要进行测试的方法上右键->goto->test 然后就idea就可以自动生成单元测试类

在单元测试类上编著

@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GrilControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void girlList() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/girls")).andExpect(
                MockMvcResultMatchers.status().isOk());
    }

}