統(tǒng)一異常處理
系統(tǒng)有一個(gè)統(tǒng)一異常處理的功能,可減少重復(fù)代碼,又便于維護(hù)。
用@ControllerAdvice和@ExceptionHandler兩個(gè)注解來(lái)做異常的統(tǒng)一處理。
@ControllerAdvice:作用于所有@Controller標(biāo)注的Controller類
@ExceptionHandler:作用于所有@RequestMapping標(biāo)注的方法拋出的指定類型的異常。
代碼實(shí)例
ExceptionHandlerAdvice.java
package com.restfeel.advice
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.context.request.WebRequest
import org.springframework.web.servlet.ModelAndView
/**
* Created by jack on 2017/3/30.
*
* 系統(tǒng)全局統(tǒng)一異常處理
*/
@ControllerAdvice
class ExceptionHandlerAdvice {
@ExceptionHandler(value = Exception::class) //表示捕捉到所有的異常,你也可以捕捉一個(gè)你自定義的異常
fun exception(exception: Exception, request: WebRequest): ModelAndView {
val modelAndView = ModelAndView("jsp/error")//error頁(yè)面
modelAndView.addObject("errorMessage", exception.message)
modelAndView.addObject("stackTrace", exception.stackTrace)
return modelAndView
}
}
error.jsp
<%--
Created by IntelliJ IDEA.
User: jack
Date: 2017/3/30
Time: 02:08
To change this template use File | Settings | File Templates.
--%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions"
prefix="fn" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<jsp:include page="header.jsp"></jsp:include>
</head>
<body>
<jsp:include page="top-nav.jsp"></jsp:include>
<div class="col-sm-12">
<h1>系統(tǒng)異常統(tǒng)一處理</h1>
<h3>${errorMessage}></h3>
<h2>Debug</h2>
<a
class="btn btn-primary btn-lg" target="_blank" id="Google">Google</a>
<a class="btn btn-info btn-lg" target="_blank" id="Baidu">Baidu</a>
<a
class="btn btn-default btn-lg" target="_blank" id="StackOverFlow">StackOverFlow</a>
<h2>異常堆棧跟蹤日志StackTrace</h2>
<code>
<c:forEach items="${stackTrace}" var="line">
${line}
</c:forEach>
</code>
</div>
<footer class="panel-footer rest-footer">
<div class="footer-nav">
<a href="/" target="_blank" hidefocus="true">RestFeel</a>
|
<a target="_blank">光劍免費(fèi)圖書館</a>
|
<a target="_blank">博客</a>
|
<a href="#" target="_blank" hidefocus="true">微信公眾號(hào):ols-lightshadow</a>
</div>
<div class="copyright">RestFeel 2017-7017</div>
</footer>
<!-- JavaScript -->
<script data-main="js/main" src="js/libs/require/require.js"></script>
<script type="text/javascript">
$(function () {
$('#Google').click()
$('#Baidu').click()
$('#StackOverFlow').click()
})
</script>
</body>
</html>
源碼工程:
https://github.com/Jason-Chen-2017/restfeel
運(yùn)行

系統(tǒng)異常統(tǒng)一處理

螢?zāi)豢煺?2017-03-30 13.29.14.png

螢?zāi)豢煺?2017-03-30 13.29.04.png

螢?zāi)豢煺?2017-03-30 13.28.55.png
這個(gè)思路很有實(shí)用價(jià)值,大大減少了系統(tǒng)出問(wèn)題debug,去賦值粘貼到google,baidu, stackoverflow的手工操作。歡迎試用。