SpringBoot全局異常攔截與自定義錯(cuò)誤頁面實(shí)現(xiàn)過程解讀
一、引言
在開發(fā)基于Spring Boot的應(yīng)用程序時(shí),異常處理是一個(gè)至關(guān)重要的環(huán)節(jié)。合理的異常處理機(jī)制不僅可以提高系統(tǒng)的穩(wěn)定性和可靠性,還能為用戶提供友好的錯(cuò)誤反饋。
本文將深入探討Spring Boot中全局異常攔截與自定義錯(cuò)誤頁面的實(shí)現(xiàn),旨在幫助技術(shù)人員掌握這一關(guān)鍵技能。
二、Spring Boot異常處理基礎(chǔ)
2.1 異常的分類
在Java中,異常分為受檢查異常(Checked Exception)和非受檢查異常(Unchecked Exception)。
受檢查異常通常是程序在編譯時(shí)就需要處理的異常,如IOException;非受檢查異常一般是運(yùn)行時(shí)異常,如NullPointerException、ArrayIndexOutOfBoundsException等。
2.2 Spring Boot默認(rèn)異常處理機(jī)制
Spring Boot為我們提供了默認(rèn)的異常處理機(jī)制。當(dāng)應(yīng)用程序拋出異常時(shí),Spring Boot會(huì)根據(jù)異常類型返回相應(yīng)的HTTP狀態(tài)碼和錯(cuò)誤信息。例如,當(dāng)發(fā)生404錯(cuò)誤時(shí),會(huì)返回一個(gè)包含錯(cuò)誤信息的JSON響應(yīng)。
下面是一個(gè)簡單的Spring Boot應(yīng)用示例:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/test")
public String test() {
throw new RuntimeException("Test exception");
}
}
當(dāng)訪問/test路徑時(shí),Spring Boot會(huì)返回一個(gè)包含錯(cuò)誤信息的JSON響應(yīng)。
三、全局異常攔截實(shí)現(xiàn)
3.1 自定義異常處理器
為了實(shí)現(xiàn)全局異常攔截,我們可以創(chuàng)建一個(gè)自定義的異常處理器類,使用@ControllerAdvice和@ExceptionHandler注解。@ControllerAdvice注解用于定義全局異常處理器,@ExceptionHandler注解用于指定處理的異常類型。
以下是一個(gè)簡單的全局異常處理器示例:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleRuntimeException(RuntimeException e) {
return new ResponseEntity<>("Runtime exception occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
在上述代碼中,GlobalExceptionHandler類使用@ControllerAdvice注解標(biāo)記為全局異常處理器,handleRuntimeException方法使用@ExceptionHandler注解指定處理RuntimeException類型的異常。
3.2 處理不同類型的異常
除了處理RuntimeException,我們還可以處理其他類型的異常。
例如,處理NullPointerException和IllegalArgumentException:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<String> handleNullPointerException(NullPointerException e) {
return new ResponseEntity<>("Null pointer exception occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException e) {
return new ResponseEntity<>("Illegal argument exception occurred: " + e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
3.3 自定義異常類
在實(shí)際開發(fā)中,我們可以創(chuàng)建自定義異常類,以便更好地管理和處理特定業(yè)務(wù)場景下的異常。
例如,創(chuàng)建一個(gè)自定義的業(yè)務(wù)異常類:
public class BusinessException extends RuntimeException {
public BusinessException(String message) {
super(message);
}
}
然后在全局異常處理器中處理該自定義異常:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<String> handleBusinessException(BusinessException e) {
return new ResponseEntity<>("Business exception occurred: " + e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
四、自定義錯(cuò)誤頁面實(shí)現(xiàn)
4.1 基本原理
Spring Boot允許我們自定義錯(cuò)誤頁面,當(dāng)發(fā)生特定的HTTP狀態(tài)碼錯(cuò)誤時(shí),會(huì)自動(dòng)跳轉(zhuǎn)到相應(yīng)的錯(cuò)誤頁面。
我們可以在src/main/resources/templates目錄下創(chuàng)建錯(cuò)誤頁面文件,文件名格式為error-{status}.html,其中{status}為HTTP狀態(tài)碼。
4.2 創(chuàng)建自定義錯(cuò)誤頁面
以下是一個(gè)簡單的404錯(cuò)誤頁面示例(error-404.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>404 Not Found</title>
</head>
<body>
<h1>404 Not Found</h1>
<p>The requested resource was not found.</p>
</body>
</html>
同樣,我們可以創(chuàng)建500錯(cuò)誤頁面(error-500.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>500 Internal Server Error</title>
</head>
<body>
<h1>500 Internal Server Error</h1>
<p>An unexpected error occurred on the server.</p>
</body>
</html>
4.3 配置錯(cuò)誤頁面
在Spring Boot中,默認(rèn)情況下會(huì)自動(dòng)查找src/main/resources/templates目錄下的錯(cuò)誤頁面。如果需要自定義錯(cuò)誤頁面的位置,可以在application.properties或application.yml中進(jìn)行配置。
在application.properties中配置:
server.error.path=/error spring.mvc.view.prefix=/templates/ spring.mvc.view.suffix=.html
在application.yml中配置:
server:
error:
path: /error
spring:
mvc:
view:
prefix: /templates/
suffix: .html
五、集成全局異常攔截與自定義錯(cuò)誤頁面
5.1 異常處理與錯(cuò)誤頁面結(jié)合
在全局異常處理器中,我們可以根據(jù)異常類型返回不同的HTTP狀態(tài)碼,從而跳轉(zhuǎn)到相應(yīng)的錯(cuò)誤頁面。例如:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<Void> handleRuntimeException(RuntimeException e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<Void> handleIllegalArgumentException(IllegalArgumentException e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
當(dāng)發(fā)生RuntimeException時(shí),會(huì)返回500狀態(tài)碼,跳轉(zhuǎn)到error-500.html頁面;當(dāng)發(fā)生IllegalArgumentException時(shí),會(huì)返回400狀態(tài)碼,跳轉(zhuǎn)到error-400.html頁面。
5.2 測試與驗(yàn)證
啟動(dòng)Spring Boot應(yīng)用程序,訪問不同的路徑,觸發(fā)不同類型的異常,驗(yàn)證全局異常攔截和自定義錯(cuò)誤頁面是否正常工作。
六、總結(jié)
通過本文的介紹,我們了解了Spring Boot中全局異常攔截與自定義錯(cuò)誤頁面的實(shí)現(xiàn)方法。
全局異常攔截可以幫助我們統(tǒng)一處理應(yīng)用程序中的異常,提高代碼的可維護(hù)性和系統(tǒng)的穩(wěn)定性;自定義錯(cuò)誤頁面可以為用戶提供更友好的錯(cuò)誤反饋,提升用戶體驗(yàn)。
在實(shí)際開發(fā)中,我們可以根據(jù)具體需求靈活運(yùn)用這些技術(shù),打造更加健壯和易用的Spring Boot應(yīng)用程序。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合Mybatis與thymleft實(shí)現(xiàn)增刪改查功能詳解
MybatisPlus是國產(chǎn)的第三方插件,?它封裝了許多常用的CURDapi,免去了我們寫mapper.xml的重復(fù)勞動(dòng)。本文將整合MybatisPlus實(shí)現(xiàn)增刪改查功能,感興趣的可以了解一下2022-12-12
spring cloud gateway跨域全局CORS配置方式
這篇文章主要介紹了spring cloud gateway跨域全局CORS配置方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
Java spring webmvc如何實(shí)現(xiàn)控制反轉(zhuǎn)
這篇文章主要介紹了Java spring webmvc如何實(shí)現(xiàn)控制反轉(zhuǎn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
mybatis+springboot發(fā)布postgresql數(shù)據(jù)的實(shí)現(xiàn)
本文主要介紹了mybatis+springboot發(fā)布postgresql數(shù)據(jù)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-11-11
mybatis插入一條數(shù)據(jù)返回相應(yīng)數(shù)據(jù)ID問題及解決
MyBatis插入數(shù)據(jù)并獲取自增ID的方法,通過設(shè)置useGeneratedKeys=true和keyProperty屬性,可以自動(dòng)將生成的ID賦值給實(shí)體對象的相應(yīng)屬性2026-05-05

