请叫我头头哥

SpringBoot入门教程(十九)@ControllerAdvice+@ExceptionHandler全局捕获Controller异常

在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中。@ControllerAdvice官方文档。创建全局异常处理类:通过使用@ControllerAdvice定义统一的异常处理类,而不是在每个Controller中逐个定义。@ExceptionHandler用来定义函数针对的异常类型,最后将Exception对象和请求URL映射到error.html中.

v新建异常捕获类

统一异常处理

package com.demo.common;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by toutou on 2018/12/9.
 */
@ControllerAdvice
public class CatchGlobalException {
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName("error");
        return mav;
    }

}

verror page

实现error.html页面展示:在templates目录下创建error.html,将请求的URL和Exception对象的message输出。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" >
<head lang="en">
    <meta charset="UTF-8" />
    <title>抱歉,这是一个错误页</title>
</head>
<body>
<div>很抱歉,这是我们的一个错误页</div>
<div>影响的因素有很多,我们会尽快解决的。  ﹃_﹃〣</div>
<div th:text="${url}"></div>
<div th:text="${exception.message}"></div>
</body>
</html>

v效果

在Controller中"创建"一个异常。

    @RequestMapping("/debug")
    public String Debug(){
        int number = 5 / 0;
        return null;
    }

运行效果如下:

SpringBoot入门教程(十九)@ControllerAdvice+@ExceptionHandler全局捕获Controller异常

v源码地址

https://github.com/toutouge/javademosecond/tree/master/hellospringboot


作  者:请叫我头头哥
出  处:http://www.cnblogs.com/toutou/
关于作者:专注于基础平台的项目开发。如有问题或建议,请多多赐教!
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
特此声明:所有评论和私信都会在第一时间回复。也欢迎园子的大大们指正错误,共同进步。或者直接私信
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是作者坚持原创和持续写作的最大动力!

posted @ 2018-12-23 21:29  请叫我头头哥  阅读(2005)  评论(0编辑  收藏  举报
//Setting ico for cnblogs