@ControllerAdvice public class ExceptionsHandler { //能够直接写@ExceptionHandler,不指明异常类,会自动映射 @ExceptionHandler(CustomGenericException.class) public ModelAndView customGenericExceptionHnadler(CustomGenericException exception){ //还能够声明接收其余任意参数 ModelAndView modelAndView = new ModelAndView("generic_error"); modelAndView.addObject("errCode",exception.getErrCode()); modelAndView.addObject("errMsg",exception.getErrMsg()); return modelAndView; } @ExceptionHandler(Exception.class)//能够直接写@EceptionHandler,IOExeption继承于Exception public ModelAndView allExceptionHandler(Exception exception){ ModelAndView modelAndView = new ModelAndView("generic_error"); modelAndView.addObject("errMsg", "this is Exception.class"); return modelAndView; } }
一、@ExceptionHandlerjava
二、@ControllerAdvicemvc
三、@ResponseStatusapp
@Controller @RequestMapping("/exception") public class ExceptionController { @RequestMapping(value = "/{type}", method = RequestMethod.GET) public ModelAndView getPages(@PathVariable(value = "type") String type) throws Exception{ if ("error".equals(type)) { // 由handleCustomException处理 throw new CustomGenericException("E888", "This is custom message"); } else if ("io-error".equals(type)) { // 由handleAllException处理 throw new IOException(); } else { return new ModelAndView("index").addObject("msg", type); } } }
四、HandlerExceptionResolver工具
五、<mvc:annotation-driven/>自动将如下三个配置到Spring MVCthis