一、错误的处理(以freemarker模板引擎为例)
方法一:Spring Boot 将所有的错误默认映射到/error, 实现ErrorController,重写getErrorPath()方法
1@Controller 2@RequestMapping(value = "error") 3public class BaseErrorController implements ErrorController { 4private static final Logger logger = LoggerFactory.getLogger(BaseErrorController.class); 5 6 @Override 7 public String getErrorPath() { 8 logger.info("出错啦!进入自定义错误控制器"); 9 return "error/error"; 10 } 11 12 @RequestMapping 13 public String error() { 14 return getErrorPath(); 15 } 16 17}
方法二:添加自定义的错误页面
2.1 html静态页面:在resources/public/error/ 下定义(请求的路径不存在)
如添加404页面: resources/public/error/404.html页面,中文注意页面编码
2.2 模板引擎页面:在templates/error/下定义(运行时异常)
如添加5xx页面: templates/error/5xx.ftl
注:templates/error/ 这个的优先级比较 resources/public/error/高
方法三:使用注解@ControllerAdvice(对特定异常处理)
1import org.slf4j.Logger; 2import org.slf4j.LoggerFactory; 3import org.springframework.http.HttpStatus; 4import org.springframework.web.bind.annotation.ControllerAdvice; 5import org.springframework.web.bind.annotation.ExceptionHandler; 6import org.springframework.web.bind.annotation.ResponseStatus; 7import org.springframework.web.servlet.ModelAndView; 8 9/** 10 * 异常处理类 11 * 12 * @author hugovon 13 * @version 1.0 14 */ 15@ControllerAdvice 16public class ErrorExceptionHandler { 17 18 private static final Logger logger = LoggerFactory.getLogger(ErrorExceptionHandler.class); 19 20 /** 21 * 统一异常处理 22 * 23 * @param exception 24 * exception 25 * @return 26 */ 27 @ExceptionHandler({ RuntimeException.class }) 28 @ResponseStatus(HttpStatus.OK) 29 public ModelAndView processException(RuntimeException exception) { 30 logger.info("自定义异常处理-RuntimeException"); 31 ModelAndView m = new ModelAndView(); 32 m.addObject("roncooException", exception.getMessage()); 33 m.setViewName("error/500"); 34 return m; 35 } 36 37 /** 38 * 统一异常处理 39 * 40 * @param exception 41 * exception 42 * @return 43 */ 44 @ExceptionHandler({ Exception.class }) 45 @ResponseStatus(HttpStatus.OK) 46 public ModelAndView processException(Exception exception) { 47 logger.info("自定义异常处理-Exception"); 48 ModelAndView m = new ModelAndView(); 49 m.addObject("roncooException", exception.getMessage()); 50 m.setViewName("error/500"); 51 return m; 52 } 53 54}