全部异常处理


全局异常处理

简介

当程序出现异常进行全局处理,SpringBoot默认异常提示:Whitelabel Error Page

解决

定义错误码页面

创建错误静态码.html,放在templates/error目录下,当发生错误时会自动到该目录下查找对应的错误码页面。
可以创建如4xx.html或者5xx.html页面,用来匹配所有该类型的错误(会先进行精确匹配)

<body>
<h2>5xx错误</h2>

<h3>状态码:[[${status}]]</h3>
<h3>错误提示:[[${error}]]</h3>
<h3>异常情况:[[${message}]]</h3>
<h3>时间戳:[[${timestamp}]]</h3>
</body>

定义异常通知

@ControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(ArithmeticException.class)

    public String arithmetic(Exception e, Model  model)
    {
       
        System.out.println("执行你干的事情,发邮件、短信给管理员");
        return "error/5xx";
    }

    @ExceptionHandler(Exception.class)

    public String exception(Exception e)
    {
        System.out.println("执行你干的事情,发邮件、短信给管理员");
        return "error/5xx";
    }
}

posted @ 2018-12-24 15:22  小朋友写代码  阅读(174)  评论(0编辑  收藏  举报