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

异常处理2

This commit is contained in:
程序员小墨 2022-03-01 18:32:59 +08:00
parent 15c78e21bd
commit 79f07cb6cd
3 changed files with 18 additions and 13 deletions

View File

@ -14,12 +14,12 @@
### 本次修改通过以下方式查看👇
> http://localhost:8090/user/get?id=1
> http://localhost:8090/user/get?id=2
预期效果:
```json
{"data":{"id":1,"name":"admin","gender":2,"age":18,"telephone":"110"},"status":"success"}
{"data":{"errCode":10002,"errMsg":"未知错误"},"status":"fail"}
```
### 层次结构以User为例自上向下

View File

@ -30,7 +30,8 @@ public class UserController {
// 若获取的用户信息不存在
if (userModel == null) {
throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
userModel.setEncryptPassword("123");
// throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
}
// 将核心领域模型用户对象转化为可供UI使用的viewobject
UserVO userVO = convertFromModel(userModel);
@ -54,16 +55,19 @@ public class UserController {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Object handlerException(HttpServletRequest request,Exception ex) {
public Object handlerException(HttpServletRequest request, Exception ex) {
BusinessException businessException = (BusinessException) ex;
HashMap<Object, Object> responseData = new HashMap<>();
responseData.put("errCode",businessException.getErrCode());
responseData.put("errMsg",businessException.getErrMsg());
CommonReturnType commonReturnType = new CommonReturnType();
commonReturnType.setStatus("fail");
commonReturnType.setData(responseData);
return commonReturnType;
if (ex instanceof BusinessException) {
BusinessException businessException = (BusinessException) ex;
responseData.put("errCode", businessException.getErrCode());
responseData.put("errMsg", businessException.getErrMsg());
} else {
responseData.put("errCode", EmBusinessError.UNKNOWN_ERROR.getErrCode());
responseData.put("errMsg", EmBusinessError.UNKNOWN_ERROR.getErrMsg());
}
return CommonReturnType.create(responseData, "fail");
}
}

View File

@ -2,10 +2,11 @@ package com.cxyxiaomo.flashsale.error;
public enum EmBusinessError implements CommonError {
// 通用错误类型 00001
PARAMETER_VALIDATION_ERROR(00001,"参数不合法"),
PARAMETER_VALIDATION_ERROR(10001,"参数不合法"),
UNKNOWN_ERROR(10002,"未知错误"),
// 10000开头为用户信息相关错误定义
USER_NOT_EXIST(10001, "用户不存在");
USER_NOT_EXIST(20001, "用户不存在");
private EmBusinessError(int errCode, String errMsg) {
this.errCode = errCode;