mirror of
https://gitee.com/coder-xiaomo/flashsale
synced 2025-09-12 15:01:39 +08:00
异常处理
This commit is contained in:
@@ -6,13 +6,14 @@ 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;
|
||||
import org.apache.catalina.User;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.HashMap;
|
||||
|
||||
@Controller("user") // 允许被SpringBoot扫描到
|
||||
@RequestMapping("/user") // 通过 "/user" 访问到
|
||||
@@ -28,7 +29,7 @@ public class UserController {
|
||||
UserModel userModel = userService.getUserById(id);
|
||||
|
||||
// 若获取的用户信息不存在
|
||||
if(userModel==null){
|
||||
if (userModel == null) {
|
||||
throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
|
||||
}
|
||||
// 将核心领域模型用户对象转化为可供UI使用的viewobject
|
||||
@@ -48,4 +49,21 @@ public class UserController {
|
||||
BeanUtils.copyProperties(userModel, userVO);
|
||||
return userVO;
|
||||
}
|
||||
|
||||
// 定义ExceptionHandler解决未被Controller层吸收的Exception
|
||||
@ExceptionHandler(Exception.class)
|
||||
@ResponseStatus(HttpStatus.OK)
|
||||
@ResponseBody
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user