@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