SpringBoot @ExceptionHandler與@ControllerAdvice異常處理詳解
前言
如果能將所有類型的異常處理從各層中解耦出來,則既保證了相關(guān)處理過程的功能較單一,也實現(xiàn)了異常信息的統(tǒng)一處理和維護。幸運的是,Spring框架支持這樣的實現(xiàn)。接下來將從自定義error頁面。@ExceptionHandler注解以及@ControllerAdvice3種方式講解Spring Boot應(yīng)用的異常統(tǒng)一處理
具體處理步驟如下:
自定義error頁面
在Spring Boot Web應(yīng)用的src/main/resources/templates 目錄下添加error.html頁面 訪問發(fā)生錯誤或異常時,Spring Boot將自動找到該頁面作為錯誤頁面。Spring Boot為錯誤頁面提供了以下屬性
- timestamp 錯誤發(fā)生時間
- status HTTP狀態(tài)碼
- error 錯誤原因
- exception 異常的類名
- message 異常消息
- errors BindingResult異常里的各種錯誤
- trace 異常跟蹤信息
- path 錯誤發(fā)生時請求的URL路徑
1: 創(chuàng)建名為com.ch.ch5_3.exception的包 并在該包中創(chuàng)建名為MyException 具體代碼如下
package com.ch.ch5_3.exception;
public class MyException extends Exception {
private static final long serialVersionUID = 1L;
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
}2:創(chuàng)建控制器類TestHandleExceptionController
創(chuàng)建名為com.ch,ch5_3.controller的包 并在該包中創(chuàng)建名為TestHandleExceptionController的控制器類,在該控制器類中,在4個請求處理方法,一個是導(dǎo)航到index.html 另外三個分別拋出不同的異常 部分代碼如下
package com.ch.ch5_3.controller;
import java.sql.SQLException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
public void db() throws SQLException {
throw new SQLException("數(shù)據(jù)庫異常");
}
@RequestMapping("/my")
public void my() throws MyException {
throw new MyException("自定義異常");
}
@RequestMapping("/no")
public void no() throws Exception {
throw new Exception("未知異常");
}
}3:View視圖頁面
Thymeleaf模板默認將視圖頁面放在src/main/resources/templates目錄下。因此我們在src/main/resources/templates 目錄下新建html頁面文件,index.html和error.html
在index.html頁面中 有4個超鏈接請求,3個請求在控制器中有對應(yīng)處理,另一個請求是404錯誤
部分代碼如下

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>index</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" rel="external nofollow" rel="external nofollow" />
<!-- 默認訪問 src/main/resources/static下的css文件夾-->
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" rel="external nofollow" rel="external nofollow" />
<a th:href="@{db}" rel="external nofollow" >處理數(shù)據(jù)庫異常</a><br>
<a th:href="@{my}" rel="external nofollow" >處理自定義異常</a><br>
<a th:href="@{no}" rel="external nofollow" >處理未知錯誤</a>
<hr>
<a th:href="@{nofound}" rel="external nofollow" >404錯誤</a>
</div>
</div>
</div>
</body>
</html>error.html頁面部分代碼如下

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>error</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}" rel="external nofollow" rel="external nofollow" />
<!-- 默認訪問 src/main/resources/static下的css文件夾-->
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}" rel="external nofollow" rel="external nofollow" />
</head>
<body>
<div class="common-hint-word">
<div th:text="${#dates.format(timestamp,'yyyy-MM-dd HH:mm:ss')}"></div>
<div th:text="${message}"></div>
<div th:text="${error}"></div>
</div>
</div>
</div>
</body>
</html>@ExceptionHandler注解
上面自定義頁面并沒有處理異常,可以使用@ExceptionHandler注解處理異常,如果有一個由該注解修飾的方法,那么當任何方法拋出異常時都由它來處理
添加一個注解修飾的方法 具體代碼如下
@ExceptionHandler(value=Excetption.class)
public String handlerException(Exception e){
if(e istanceof SQLException){
return "sql error";
}
else if(e instanceof MYException){
return"myError";
}
else{
return "noerror";
}
}@ControllerAdvice注解
使用它注解的類時當前Spring Boot應(yīng)用中所有類的統(tǒng)一異常處理類,該類中使用@ExceptionHandler注解的方法統(tǒng)一處理異常,不需要在每個Controller中逐一定義異常處理方法,這是因為對所有注解了@ControllerAdvice注解進行全局異常處理
創(chuàng)建GlobalExceptionHandlerController的類 具體代碼如下
package com.ch.ch5_3.controller;
import java.sql.SQLException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.ch.ch5_3.exception.MyException;
@ControllerAdvice
public class GlobalExceptionHandlerController {
@ExceptionHandler(value=Exception.class)
public String handlerException(Exception e) {
//數(shù)據(jù)庫異常
if (e instanceof SQLException) {
return "sqlError";
} else if (e instanceof MyException) {//自定義異常
return "myError";
} else {//未知異常
return "noError";
}
}
}到此這篇關(guān)于SpringBoot @ExceptionHandler與@ControllerAdvice異常處理詳解的文章就介紹到這了,更多相關(guān)SpringBoot @ExceptionHandler與@ControllerAdvice內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatis中執(zhí)行SQL語句的幾種方式總結(jié)
MyBatis是一個優(yōu)秀的持久層框架,它支持定制化SQL、存儲過程以及高級映射,下面這篇文章主要給大家介紹了關(guān)于MyBatis中執(zhí)行SQL語句的幾種方式,需要的朋友可以參考下2024-04-04
java調(diào)用python代碼的兩種實現(xiàn)方式:Runtime.exec()和Jython
在Java中調(diào)用Python代碼有多種方法,包括使用Runtime.exec()和第三方庫如Jython,Runtime.exec()通過系統(tǒng)命令執(zhí)行Python腳本,適用于簡單的調(diào)用場景,Jython則是一個Python的Java實現(xiàn),允許在Java中直接運行Python代碼,適用于更深層次的集成需求2025-01-01

