springboot使用@ControllerAdvice统一异常处理返回JSON格式

Java 02-08 16:42

springboot使用@ControllerAdvice统一异常处理返回JSON格式

@ControllerAdvice是Spring3.2中新增的注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping、@PostMapping, @GetMapping注解中。下面主要演示与@ExceptionHandler自定义全局异常捕捉处理。

①自定义异常类 MyException


@Data
public MyException extends RuntimeException {

// 自定义异常code
private String errCode;
// 自定义异常信息
private String errMsg;
// 自定义返回异常数据对象
private Object data;

public MyException() {
super();
}

public MyException(String errCode, String errMsg) {
this.errCode = errCode;
this,errMsg = errMsg;
}

public MyException(String errCode, String errMsg, Object data) {
this.errCode = errCode;
this,errMsg = errMsg;
this.data = data;
}
}

②自定义全局异常处理 MyExceptionHandler


@ControllerAdvice
public MyExceptionHandler {
// 处理自定义的异常
@ResponseBody
@ExceptionHandler(value = MyException.class) // 指定需要拦截的异常类
public ResultVO myExceptionHandler(MyException exception) {
return ResultVO.failKnow(exception.errCode, exception.errMsg);
}
}

③ 自定义返回统一响应体 ResultVO

package cn.cloud.tcp.comm.vo;
import java.io.Serializable;
import lombok.Data;
@Data
public class ResultVO<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer code;
    private String msg;
    public ResultVO(int code, String message) {
        this.code = code;
        this.msg = message;
    }
    public static <T> ResultVO<T> successMessage(String message) {
        ResultVO<T> resultVo = successNoData();
        resultVo.setMsg(message);
        return resultVo;
    }
    public static <T> ResultVO<T> failKnow(int code, String message) {
        return new ResultVO<>(code, message);
    }
}

④ 统一拦截器里使用


@RestController
public class TestController {
    @RequestMapping("testMyException")
    public String testMyException() throws MyException{
        throw new MyException(500,"i am a myException");
    }
}

相关推荐