public class AgeException extends UserException{ public AgeException() { } public AgeException(String message) { super(message); } } public class NameException extends UserException{ public NameException() { } public NameException(String message) { super(message); } } public class UserException extends Exception{ public UserException() { } public UserException(String message) { super(message); } }
@Controller @RequestMapping("/user") public class UserController { @RequestMapping("/some") public ModelAndView doSome(String name,Integer age) throws UserException { ModelAndView modelAndView = new ModelAndView(); if(!name.equals("黄振聪")){ throw new NameException("用户:"+name+"不是黄振聪!"); } if(age == null || age > 100){ throw new AgeException("年龄不符合要求!"); } modelAndView.addObject("uname",name); modelAndView.addObject("uage",age); modelAndView.setViewName("target"); return modelAndView; } }
@ControllerAdvice public class UserExceptionHandler { /** @ExceptionHandler: 属性: value:指定异常类,若没有指定则表示其他所有异常 */ @ExceptionHandler(value = NameException.class) public ModelAndView nameException(Exception ex){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("tips","处理NameException"); modelAndView.addObject("ex",ex); modelAndView.setViewName("nameError"); return modelAndView; } @ExceptionHandler(value = AgeException.class) public ModelAndView ageException(Exception ex){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("tips","处理AgeException"); modelAndView.addObject("ex",ex); modelAndView.setViewName("ageError"); return modelAndView; } @ExceptionHandler public ModelAndView otherException(Exception ex){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("ex",ex); modelAndView.setViewName("otherError"); return modelAndView; } }
<context:component-scan base-package="com.hzc.controller" /> <context:component-scan base-package="com.hzc.handler" /> <mvc:annotation-driven />
结构图: