大体流程图
1、异常的枚举
public enum ErrorEnum {
/**
*请求成功
*/
SUCCESS(200,"成功"),
/**
*参数异常
*/
PARAM(400,"参数异常"),
/**
*系统异常
*/
EXCEPTION(500,"系统异常");
private Integer code;
private String msg;
private ErrorEnum(Integer code,String msg){
this.code=code;
this.msg=msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
2、异常类
public class BaseException extends RuntimeException {
private Integer code;
private String msg;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public BaseException(ErrorEnum errorEnum) {
this.code = errorEnum.getCode();
this.msg = errorEnum.getMsg();
}
}
3、异常处理类
@RestControllerAdvice
public class ExceptionHandler {
//拦截自己定义的异常
@org.springframework.web.bind.annotation.ExceptionHandler(value = BaseException.class)
public ResponseResult<Object> baseException(BaseException e){
return new ResponseResult<>(e.getCode(),e.getMsg(),null);
}
//拦截Exception异常
@org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
public ResponseResult<Object> baseException(Exception e){
return new ResponseResult<>(ErrorEnum.EXCEPTION.getCode(),ErrorEnum.EXCEPTION.getMsg(),null);
}
4、返回对象
public class ResponseResult<T> {
private Integer code;
private String msg;
private T data;
public Integer getCode() {
return code;
}
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;
}
public ResponseResult(Integer code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
}
5、返回封装类
public class RespGenerator {
//成功返回
public ResponseResult success(Object data){
return new ResponseResult(ErrorEnum.SUCCESS.getCode(), "请求成功",data);
}
//失败返回
public ResponseResult fail(BaseException baseException){
return new ResponseResult(baseException.getCode(), baseException.getMsg(), null);
}
}
6、控制层–测试
@RestController
@RequestMapping("/test")
public class TestController extends RespGenerator {
@RequestMapping("/demo")
public ResponseResult<Object> testException(String name){
if (StringUtils.isEmpty(name)){
return fail(new BaseException(ErrorEnum.PARAM));
}
return success(null);
}
}
结果