From 15c78e21bd03688acce70c357407aec91b9b5b13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=BA=8F=E5=91=98=E5=B0=8F=E5=A2=A8?= <2291200076@qq.com> Date: Tue, 1 Mar 2022 18:26:36 +0800 Subject: [PATCH] =?UTF-8?q?=E5=BC=82=E5=B8=B8=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../flashsale/controller/UserController.java | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/cxyxiaomo/flashsale/controller/UserController.java b/src/main/java/com/cxyxiaomo/flashsale/controller/UserController.java index 5269571..446b524 100644 --- a/src/main/java/com/cxyxiaomo/flashsale/controller/UserController.java +++ b/src/main/java/com/cxyxiaomo/flashsale/controller/UserController.java @@ -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 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; + } }