Spring Boot 请求错误处理

方法一:Spring Boot将所有的错误映射到/error,实现ErrorController接口

 1 @Controller
 2 @RequestMapping("/error")
 3 public class BaseErrorController implements ErrorController {
 4     private 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 }

 

         

请求一个错误的地址:localhost:8080/asdf,就会跳转到 error/error.ftl 页面。

 ==============================================================

方法二:添加自定义的错误页面(前提:没有实现ErrorController接口)

2.1 添加 html 静态页面:在resources/public/error/下定义

    如添加404页面:resources/public/error/404.html页面(中文注意页面编码)

2.2 添加模板引擎页面:在templates/error下定义

    如添加5xx页面:templates/error/5xx.ftl;

    添加404页面: templates/error/404.ftl 。

注:templates/error/ 这个的优先级比 resources/public/error/ 的优先级高。

==============================================================

方法三:使用注解@ControllerAdvice

@ControllerAdvice
public class BaseException {
    private final Logger logger = LoggerFactory.getLogger(BaseException.class);

    /**
     * 统一异常处理
     *
     * @param exception
     * @return
     */
    @ExceptionHandler({RuntimeException.class})//拦截运行时异常(可以拦截自定义异常)
    @ResponseStatus(HttpStatus.OK)
    public ModelAndView processException(RuntimeException exception) {
        logger.info("自定义异常处理--RuntimeException");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exceptionMsg", exception.getMessage());
        modelAndView.setViewName("error/500");
        return modelAndView;
    }

    /**
     * 统一异常处理
     * @param exception
     * @return
     */
    @ExceptionHandler({Exception.class})//拦截总异常
    @ResponseStatus(HttpStatus.OK)
    public ModelAndView processException(Exception exception) {
        logger.info("自定义异常处理--Exception");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exceptionMsg", exception.getMessage());
        modelAndView.setViewName("error/500");
        return modelAndView;
    }

}

 

在templates/error下创建500.ftl 来接收展示 ${exceptionMsg}。

 

posted on 2017-09-19 22:49  whlshot  阅读(343)  评论(0编辑  收藏  举报

导航