1
0
mirror of https://gitee.com/coder-xiaomo/flashsale synced 2025-01-10 11:48:14 +08:00
Code Issues Projects Releases Wiki Activity GitHub Gitee

定义通用的返回对象--返回错误信息

This commit is contained in:
程序员小墨 2022-03-01 18:15:53 +08:00
parent 9a83cc0233
commit c300bc6ce4
5 changed files with 90 additions and 2 deletions

View File

@ -42,4 +42,6 @@
**Tips:** Model与Data Object并非完全一一对应例如UserModel是由ServiceImpl将UserDO和UserPasswordDO组装而成的。
response: 用于处理HTTP请求返回
response: 用于处理HTTP请求返回
error: 用于返回错误信息

View File

@ -1,6 +1,8 @@
package com.cxyxiaomo.flashsale.controller;
import com.cxyxiaomo.flashsale.controller.viewobject.UserVO;
import com.cxyxiaomo.flashsale.error.BusinessException;
import com.cxyxiaomo.flashsale.error.EmBusinessError;
import com.cxyxiaomo.flashsale.response.CommonReturnType;
import com.cxyxiaomo.flashsale.service.UserService;
import com.cxyxiaomo.flashsale.service.model.UserModel;
@ -21,9 +23,14 @@ public class UserController {
@RequestMapping("/get")
@ResponseBody
public CommonReturnType getUser(@RequestParam(name = "id") Integer id) {
public CommonReturnType getUser(@RequestParam(name = "id") Integer id) throws BusinessException {
// 调用Services服务获取对应id的用户对象并返回给前端
UserModel userModel = userService.getUserById(id);
// 若获取的用户信息不存在
if(userModel==null){
throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
}
// 将核心领域模型用户对象转化为可供UI使用的viewobject
UserVO userVO = convertFromModel(userModel);

View File

@ -0,0 +1,37 @@
package com.cxyxiaomo.flashsale.error;
/**
* 包装器业务异常类实现
*/
public class BusinessException extends Exception implements CommonError {
private CommonError commonError;
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 this.commonError.getErrCode();
}
@Override
public String getErrMsg() {
return this.commonError.getErrMsg();
}
@Override
public CommonError setErrMsg(String errMsg) {
this.commonError.setErrMsg(errMsg);
return this;
}
}

View File

@ -0,0 +1,7 @@
package com.cxyxiaomo.flashsale.error;
public interface CommonError {
public int getErrCode();
public String getErrMsg();
public CommonError setErrMsg(String errMsg);
}

View File

@ -0,0 +1,35 @@
package com.cxyxiaomo.flashsale.error;
public enum EmBusinessError implements CommonError {
// 通用错误类型 00001
PARAMETER_VALIDATION_ERROR(00001,"参数不合法"),
// 10000开头为用户信息相关错误定义
USER_NOT_EXIST(10001, "用户不存在");
private EmBusinessError(int errCode, String errMsg) {
this.errCode = errCode;
this.errMsg = errMsg;
}
private int errCode;
private String errMsg;
@Override
public int getErrCode() {
return this.errCode;
}
@Override
public String getErrMsg() {
return this.errMsg;
}
@Override
public CommonError setErrMsg(String errMsg) {
this.errCode = errCode;
this.errMsg = errMsg;
return this;
}
}