全局异常处理
文章目录
全局异常处理指的是针对程序中产生的Exception进行的处理。产生了异常之后,可以统一跳转到一个页面进行错误提示,也可以通过Restful形式返回错误信息。
全局错误指的是对http状态进行的错误跳转处理。
全局异常指的是发生某些异常(如果处理的是Exception,则表示处理全部异常)之后的跳转页面。
eg:
1、建立一个全局异常处理,可以处理所有的Exception异常。
GlobalException.java
@ControllerAdvice // 作为一个控制层的切面处理
public class GlobalExceptionAdvice {
public static final String DEFAULT_ERROR_VIEW = "error"; // 定义错误显示页,error.html
@ExceptionHandler(Exception.class) // 处理所有Exception类
public ModelAndView defaultErrorHandler(HttpServletRequest request,
Exception e) { // 出现异常之后会跳转到此方法
ModelAndView mav = new ModelAndView(DEFAULT_ERROR_VIEW); // 设置跳转路径
//跳转到error页面
mav.addObject("exception", e); // 保存异常信息
mav.addObject("url", request.getRequestURL()); // 获得请求的路径
return mav;
}
}
2、建立个error.html页面,进行错误信息显示。
view/templates
error.html
显示错误路径 错误信息 进行错误信息显示。
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>全局异常处理</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
<p th:text="${'错误路径:' + url}"/>
<p th:text="${'错误信息:' + exception.message}"/>
</body>
</html>
3、建立一个控制器,来产生一个异常信息,观察全局异常处理是否生效。
搞个异常来
@RestController
public class ExceptionController {
@GetMapping("/exception")
public String exception() {
//搞个异常来
int a = 10 / 0;
return "liuawen.cn" ;
}
}
执行,浏览器访问一波 http://localhost/exception
访问/exception路径,就会产生异常,而产生异常之后将统一跳转到error.html页面。
<html><head>
<title>全局异常处理</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
</head>
<body>
<p>错误路径:http://localhost/exception</p>
<p>错误信息:/ by zero</p>
<div id="gtx-trans" style="position: absolute; left: 232px; top: 75.2857px;"><div class="gtx-trans-icon"></div></div></body></html>
错误路径:http://localhost/exception
错误信息:/ by zero
4、基于Restful错误信息提示。 返回一波JSON格式的
可以直接采用Restful的形式回应异常信息,不再跳转到HTML页面进行显示。
直接返回JOSN格式的。
修改GlobalExceptionAdvice程序类,将其修改为Restful风格显示。
@RestControllerAdvice // 使用Rest风格返回
public class GlobalExceptionAdvice {
@ExceptionHandler(Exception.class) // 处理所有异常
public Object defaultErrorHandler(HttpServletRequest request,Exception e) {
class ErrorInfo { // 错误提示信息
private Integer code ;
private String message ;
private String url ;
// setter、getter略
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
ErrorInfo info = new ErrorInfo() ;
info.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());// 状态码
info.setMessage(e.getMessage()); // 保存错误信息
info.setUrl(request.getRequestURL().toString()); // 保存错误路径
return info ;
}
}
使用了@RestControllerAdvice注解,则此时的异常处理将使用Restful风格,=
将对象转换为JSON格式的 显示到页面上。
http://localhost/exception
<html><head></head><body><link rel="stylesheet" type="text/css" href="chrome-extension://noinamigmjeiacnfhjibpfpmnckdoaog/jsonview-core.css"><style>body {
white-space: pre;
font-family: monospace;
}
.property {
font-weight: bold;
}
.type-null {
color: gray;
}
.type-boolean {
color: firebrick;
}
.type-number {
color: blue;
}
.type-string {
color: green;
}
.callback-function {
color: gray;
}
.collapser:after {
content: "-";
}
.collapsed > .collapser:after {
content: "+";
}
.ellipsis:after {
content: " … ";
}
.collapsible {
margin-left: 2em;
}
.hoverable {
padding-top: 1px;
padding-bottom: 1px;
padding-left: 2px;
padding-right: 2px;
border-radius: 2px;
}
.hovered {
background-color: rgba(235, 238, 249, 1);
}
.collapser {
padding-right: 6px;
padding-left: 6px;
}</style><div id="json"><div class="collapser"></div>{<span class="ellipsis"></span><ul class="obj collapsible"><li><div class="hoverable"><span class="property">code</span>: <span class="type-number">500</span>,</div></li><li><div class="hoverable"><span class="property">message</span>: <span class="type-string">"/ by zero"</span>,</div></li><li><div class="hoverable"><span class="property">url</span>: <span class="type-string">"</span><a href="http://localhost/exception">http://localhost/exception</a><span class="type-string">"</span></div></li></ul>}</div><div class="status"></div><div class="toolbox"><span title="expand all">+</span><span title="reduce all">-</span><a target="_blank" href="view-source:http://localhost/exception">View source</a><img title="options" src="chrome-extension://noinamigmjeiacnfhjibpfpmnckdoaog/options.png"></div></body></html>
程序发生异常之后的运行效果 页面显示下面的
{
code: 500,
message: "/ by zero",
url: "http://localhost/exception"
}
5、参考资料
简单记录
1、名师讲坛:Java微服务架构实战(SpringBoot+SpringCloud+Docker+RabbitMQ)- 李兴华