在项目中,一般会对数据返回格式做一个统一的要求包括遇到的各种各样业务异常
1.定义返回的数据格式
package com.lhr.springbootlearning.VO;
import lombok.Data;
import java.io.Serializable;
/**
* Created by lhr
* 2018/10/22 20:33
*/
@Data
public class ResultVO implements Serializable {
private static final long serialVersionUID = 3068837394742385883L;
/**
* 错误信息.
*/
private String msg;
/**
* 错误码.
*/
private Integer code;
/**
* 返回具体内容.
*/
private T data;
}
2.定义返回数据的方法
package com.lhr.springbootlearning.utils;
import com.lhr.springbootlearning.VO.ResultVO;
/**
* Created by lhr
* 2018/10/22 21:28
*/
public class ResultVOUtil {
public static ResultVO success(Object object) {
ResultVO resultVO = new ResultVO();
resultVO.setMsg("success");
resultVO.setCode(0);
resultVO.setData(object);
return resultVO;
}
public static ResultVO success() {
return success(null);
}
public static ResultVO error(Integer code, String msg) {
ResultVO resultVO = new ResultVO();
resultVO.setCode(code);
resultVO.setMsg(msg);
return resultVO;
}
}
3.定义异常信息的枚举
package com.lhr.springbootlearning.enums;
import lombok.Getter;
/**
* Created by lhr
* 2018/10/24 15:50
*/
@Getter
public enum ResultEnum {
SUCCESS(0, "成功"),
PARAM_ERROR(1, "参数不正确"),
PRODUCT_NOT_EXIST(10, "商品不存在"),
PRODUCT_STOCK_ERROR(11, "商品库存不正确"),
;
private Integer code;
private String message;
ResultEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
}
4.封装自定义异常
package com.lhr.springbootlearning.exception;
import com.lhr.springbootlearning.enums.ResultEnum;
import lombok.Getter;
/**
* Created by lhr
* 2018/10/24 15:08
*/
@Getter
public class SellException extends RuntimeException {
private Integer code;
public SellException(ResultEnum resultEnum) {
super(resultEnum.getMessage());
this.code = resultEnum.getCode();
}
public SellException(Integer code, String message) {
super(message);
this.code = code;
}
}
5.全局异常处理
package com.lhr.springbootlearning.exception;
import com.lhr.springbootlearning.VO.ResultVO;
import com.lhr.springbootlearning.utils.ResultVOUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 全局异常
* Created by lhr
* 2018/10/31 17:19
*/
@ControllerAdvice
public class ExceptionHandle {
@ExceptionHandler(value = SellException.class)
@ResponseBody
public ResultVO handlerException(SellException e) {
return ResultVOUtil.error(e.getCode(), e.getMessage());
}
}
注:
@ControllerAdvice:定义统一的异常处理类
@ExceptionHandler:异常处理器,当出现其定义的异常时进行处理的方法,可传入多个需要捕获的异常类
使用:
/**
* 创建订单
*/
@PostMapping("/create")
public ResultVO