SpringBoot開發中實現對前端返回數據的一致及錯誤異常統一處理
我們要做的事向前端返回的統一的json格式的數據,在這裏定義一個通用的返回類
//統一返回
public class CommonReturnType {
//表名請求的返回處理結果 success或者fail
private String status;
//若status=success,則返回前端json數據
//若status=fail,則返回前端通用錯誤碼
private Object data;
//定義一個通用的創建方法
public static CommonReturnType create(Object result){
return CommonReturnType.create(result,"success");
}
public static CommonReturnType create(Object result, String status) {
CommonReturnType type=new CommonReturnType();
type.setStatus(status);
type.setData(result);
return type;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
格式爲 status + data
在成功的時候直接調用這個類返回
在這裏我們在controller層進行了處理
@Controller("user")
@RequestMapping("/user")
public class UserController extends BaseController{
@Autowired
private UserService userService;
@RequestMapping("/get")
@ResponseBody
public CommonReturnType getUser(@RequestParam(name="id") Integer id) throws BusinessException {
//調用service服務獲取用戶的對象返回給前端
UserModel userModel = userService.getUserById(id);
//若獲取的對應用戶信息不存在
if(userModel==null){
throw new BusinessException(EmBusinessError.USER_NOT_EXIST); //拋異常
}
// //將核心領域模型轉化爲UI使用的Object
// return convertFromModek(userModel);
UserVO userVO = convertFromModek(userModel);
//返回通用對象
return CommonReturnType.create(userVO);
}
private UserVO convertFromModek(UserModel userModel){
if(userModel==null){
return null;
}
UserVO userVO=new UserVO();
BeanUtils.copyProperties(userModel,userVO);
return userVO;
}
}
在這裏當獲取數據成功的時候就返回成功的狀態加上成功獲取的數據
但在失敗的時候我們也需要將錯誤的信息傳給用戶,而不是直接顯示服務器向頁面返回的錯誤信息
先定義個相關的接口
public interface CommonError {
public int getErrCode();
public String getErrMsg();
public CommonError setErrMsg(String errMsg);
}
在這裏我們要創建一個用於挪列所有錯誤的枚舉類
public enum EmBusinessError implements CommonError {
//通用錯誤類型00001
PARAMETER_VALIDATION_ERROR(10001,"參數不合法"),
UNKNOWN_ERROR(10002,"未知錯誤"),
//10000開頭爲爲用戶信息相關的錯誤定義
USER_NOT_EXIST(20001,"用戶不存在")
;
private int errCode;
private String errMsg;
EmBusinessError(int errCode, String errMsg) {
this.errCode=errCode;
this.errMsg=errMsg;
}
@Override
public int getErrCode() {
return errCode;
}
@Override
public String getErrMsg() {
return errMsg;
}
@Override
public CommonError setErrMsg(String errMsg) {
this.errMsg=errMsg;
return this;
}
}
在定義相關的一異常類,在拋異常的時候我們要用到這個異常類
public class BusinessException extends Exception implements CommonError{
private CommonError commonError;
//接收EmBussinessError的傳參用於構造業務異常
public BusinessException(CommonError commonError){
super();
this.commonError=commonError;
}
//接收errMsg的方式構造業務異常
public BusinessException(CommonError commonError,String errMsg){
super();
this.commonError=commonError;
this.commonError.setErrMsg(errMsg);
}
@Override
public int getErrCode() {
return commonError.getErrCode();
}
@Override
public String getErrMsg() {
return commonError.getErrMsg();
}
@Override
public CommonError setErrMsg(String errMsg) {
this.setErrMsg(errMsg);
return this;
}
}
我們剛纔已經在Controller層定義了對獲取到的用戶進行檢測,如果是空的話就跑一個異常,然後SpringBoot有專門的處理異常的程序
我們在這裏來定義它,創建一個基類,到時候讓所有的Controller層都繼承他,也就默認把這個方法添加到控制器中了
mport com.miaoshaproject.error.BusinessException;
import com.miaoshaproject.error.EmBusinessError;
import com.miaoshaproject.response.CommonReturnType;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
public class BaseController {
//定義excptionHandler解決違背controller層吸收的exception
@ExceptionHandler(Exception.class) //指定,當出現Exception這個異常的時候就執行相關的代碼
@ResponseStatus(HttpStatus.OK) //讓他以正常的狀態返回
@ResponseBody
public CommonReturnType handlerException(HttpServletRequest request, Exception ex){
Map<String, Object> responseData = new HashMap<>();
if(ex instanceof BusinessException) {
BusinessException businessException = (BusinessException) ex;
responseData.put("errCode", businessException.getErrCode());
responseData.put("errMsg", businessException.getErrMsg());
return CommonReturnType.create(responseData, "fail");
}else {
responseData.put("errCode",EmBusinessError.UNKNOWN_ERROR);
responseData.put("errMsg", EmBusinessError.UNKNOWN_ERROR.getErrMsg());
return CommonReturnType.create(responseData, "fail");
}
}
}
在這裏我們對所有的錯誤都進行處理,保證返回給前端的信息時固定的格式的
在這總結一下
//1.定義了一個CommonReturnType通用返回類( status + data )方式返回所有的json數據
//2.定義了一個EmBusinessError類來管理所有的異常錯誤
//3.定義了一個BaseController來處理在Controller層的所有異常