今天敲了会代码,想用@ExceptionHandler处理异常试试。
写好一段程序后,抛异常怎么也走不进@ExceptionHandler修饰的方法,大家帮忙看看。
package cn.net.bysoft.blackpearl.controller;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController;
import cn.net.bysoft.blackpearl.entity.ResponseInfo; import cn.net.bysoft.blackpearl.entity.User; import cn.net.bysoft.blackpearl.exception.UserLockedException; import cn.net.bysoft.blackpearl.exception.UserLoginFailException; import cn.net.bysoft.blackpearl.service.UserService;
@RestController @RequestMapping(value = { "/controller/users" }) public class UserController {
@Autowired private UserService userService;
@ExceptionHandler(UserLockedException.class) @ResponseStatus(HttpStatus.LOCKED) public ResponseInfo handlerUserLocked(UserLockedException userLockedException) { return new ResponseInfo(HttpStatus.LOCKED, userLockedException.getErrMsg()); }
@ExceptionHandler(UserLoginFailException.class) @ResponseStatus(HttpStatus.NOT_FOUND) public ResponseInfo handlerUserLoginFail(UserLockedException userLockedException) { System.out.println("123"); return new ResponseInfo(HttpStatus.NOT_FOUND, userLockedException.getErrMsg()); }
@RequestMapping(value = "/login", method = RequestMethod.POST) public ResponseInfo login(@RequestBody User user, HttpSession httpSession) { // 通过帐号和密码查询用户 User currentUser = userService.findByEmailAndPassword(user);
// 判断是否查询到了用户 if (currentUser != null) { // 将用户设置在Session中 httpSession.setAttribute("User", currentUser); // 判断用户是否被锁定 if (!currentUser.isLocked()) { throw new UserLockedException("UserLocked", "您登录的帐号已被锁定。"); } } else { // 登录失败 throw new UserLoginFailException("UserNotFound", "帐号或密码不存在。"); } // 登陆成功 return new ResponseInfo(HttpStatus.OK); }
@RequestMapping(value = "/current", method = RequestMethod.GET) public ResponseInfo getCurrentUser(HttpSession httpSession) { // 从Session中获得当前用户 return new ResponseInfo(HttpStatus.OK, httpSession.getAttribute("User")); }
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
@ExceptionHandler(UserLoginFailException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseInfo handlerUserLoginFail(UserLockedException userLockedException) {
System.out.println("123");
return new ResponseInfo(HttpStatus.NOT_FOUND, userLockedException.getErrMsg());
}
参数类型写错了,弄死我吧!再也不复制粘贴了!