- 有时我们需要捕获一些更为具体的问题显示给用户,可以继承RuntimeException创建自定的异常类,在Controller方法中手动抛出自定义的异常,交给特定的异常处理器
示例
- CustomException.java
public class CustomException extends RuntimeException{ public CustomException(){ super(); }
public CustomException(String message){ super(message); } } |
- UserController.java
@Controller
public class UserController {
@RequestMapping("login")
public ModelAndView login(String userName, String age) throw CustomException{
ModelAndView mav = new ModelAndView();
mav.setViewName("welcome");
if(!userName.equals("zhangsan")){
throw new CustomException("用户名已存在"); //抛出自定义的异常
}
return mav;
}
}
- MyGlobalExceptionHandler.java
@ControllerAdvice
public class MyGlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
public ModelAndView handlerCustomException(Exception e){
System.out.println(e);
ModelAndView mav = new ModelAndView();
nav.setViewName("nameError");
nav.addObject("tips", "请更换用户名");
return nav;
}