上一篇:springboot 1.5.4 配置文件詳解(八)
1 Spring Boot統一異常處理
Spring Boot中實現了默認的error映射,但是在實際應用中,上面你的錯誤頁面對用戶來說並不夠友好,我們通常需要去實現我們自己的異常提示。
以springboot項目爲例,進行處理!
spring-boot相關項目源碼,
碼雲地址:https://git.oschina.net/wyait/springboot1.5.4.git
github地址:https://github.com/wyait/spring-boot-1.5.4.git
1.1 創建全局異常處理類
通過使用@ControllerAdvice定義統一的異常處理類,而不是在每個Controller中逐個定義。@ExceptionHandler用來定義函數針對的異常類型,最後將Exception對象和請求URL映射到error.html中(默認重定向到error.html頁面,可自定義)
/**
*
* @項目名稱:spring-boot-jsp
* @類名稱:GlobalExceptionHandler
* @類描述:全局異常處理類
* @創建人:wyait
* @創建時間:2017年6月28日下午4:06:08
* @version:
*/
@ControllerAdvice
public classGlobalExceptionHandler {
publicstatic final String DEFAULT_ERROR_VIEW = "error";
@ExceptionHandler(value= Exception.class)
publicModelAndView defaultErrorHandler(HttpServletRequest req, Exception e)
throwsException {
ModelAndViewmav = new ModelAndView();
mav.addObject("exception",e);
mav.addObject("url",req.getRequestURL());
mav.setViewName(DEFAULT_ERROR_VIEW);
returnmav;
}
}
1.2 編寫error.html
在templates目錄下創建error.html,將請求的URL和Exception對象的message輸出。
<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8"/>
<title>This is Exceptionhtml</title>
</head>
<body>
<h1>ErrorHandler</h1>
<divth:text="${url}"></div>
<divth:text="${exception.message}"></div>
</body>
</html>
在HelloController裏添加:1/0代碼。
啓動,訪問:
如果沒有exception異常,比如:404,頁面效果是:
通過實現上述內容之後,我們只需要在Controller中拋出Exception,當然我們可能會有多種不同的Exception。然後在@ControllerAdvice類中,根據拋出的具體Exception類型匹配@ExceptionHandler中配置的異常類型來匹配錯誤映射和處理。
項目源碼,
碼雲地址:https://git.oschina.net/wyait/springboot1.5.4.git
github地址:https://github.com/wyait/spring-boot-1.5.4.git
spring boot系列文章:
spring boot 1.5.4 集成devTools(五)
spring boot 1.5.4 集成JdbcTemplate(六)
spring boot 1.5.4 集成spring-Data-JPA(七)
spring boot 1.5.4 定時任務和異步調用(十)
spring boot 1.5.4 整合log4j2(十一)
spring boot 1.5.4 整合 mybatis(十二)
spring boot 1.5.4 整合 druid(十三)
spring boot 1.5.4 之監控Actuator(十四)
spring boot 1.5.4 整合webService(十五)
spring boot 1.5.4 整合redis、攔截器、過濾器、監聽器、靜態資源配置(十六)
spring boot 1.5.4 整合rabbitMQ(十七)