
- Spring Boot 教程
- Spring Boot - 首頁
- Spring Boot - 簡介
- Spring Boot - 快速入門
- Spring Boot - 引導啟動
- Spring Tool Suite
- Spring Boot - Tomcat 部署
- Spring Boot - 構建系統
- Spring Boot - 程式碼結構
- Spring Bean 與依賴注入
- Spring Boot - 執行器
- Spring Boot - 啟動器
- Spring Boot - 應用屬性
- Spring Boot - 配置
- Spring Boot - 註解
- Spring Boot - 日誌
- 構建 RESTful Web 服務
- Spring Boot - 異常處理
- Spring Boot - 攔截器
- Spring Boot - Servlet 過濾器
- Spring Boot - Tomcat 埠號
- Spring Boot - Rest Template
- Spring Boot - 檔案處理
- Spring Boot - 服務元件
- Spring Boot - Thymeleaf
- 使用 RESTful Web 服務
- Spring Boot - CORS 支援
- Spring Boot - 國際化
- Spring Boot - 定時任務
- Spring Boot - 啟用 HTTPS
- Spring Boot - Eureka 伺服器
- 使用 Eureka 註冊服務
- 閘道器代理伺服器和路由
- Spring Cloud 配置伺服器
- Spring Cloud 配置客戶端
- Spring Boot - Actuator
- Spring Boot - Admin 伺服器
- Spring Boot - Admin 客戶端
- Spring Boot - 啟用 Swagger2
- Spring Boot - 使用 SpringDoc OpenAPI
- Spring Boot - 建立 Docker 映象
- 追蹤微服務日誌
- Spring Boot - Flyway 資料庫
- Spring Boot - 傳送郵件
- Spring Boot - Hystrix
- Spring Boot - Web Socket
- Spring Boot - 批處理服務
- Spring Boot - Apache Kafka
- Spring Boot - Twilio
- Spring Boot - 單元測試用例
- Rest Controller 單元測試
- Spring Boot - 資料庫處理
- 保護 Web 應用
- Spring Boot - 使用 JWT 的 OAuth2
- Spring Boot - Google Cloud Platform
- Spring Boot - Google OAuth2 登入
- Spring Boot 資源
- Spring Boot - 快速指南
- Spring Boot - 有用資源
- Spring Boot - 討論
Spring Boot - 異常處理
在企業應用程式中,處理 API 中的異常和錯誤並向客戶端傳送正確的響應非常重要。本章我們將學習如何在 Spring Boot 中處理異常。
在繼續異常處理之前,讓我們先了解以下註解。
控制器建議 (@ControllerAdvice)
@ControllerAdvice 是一個註解,用於全域性處理異常。
您可以使用以下程式碼建立 @ControllerAdvice 類來全域性處理異常:
package com.tutorialspoint.demo.exception; import org.springframework.web.bind.annotation.ControllerAdvice; @ControllerAdvice public class ProductExceptionController { }
異常處理器 (@ExceptionHandler)
@ExceptionHandler 是一個註解,用於處理特定異常並向客戶端傳送自定義響應。
定義一個擴充套件 RuntimeException 類的類。
package com.tutorialspoint.demo.exception; public class ProductNotfoundException extends RuntimeException { private static final long serialVersionUID = 1L; }
您可以定義 @ExceptionHandler 方法來處理異常,如下所示。此方法應用於編寫 Controller Advice 類檔案。
@ExceptionHandler(value = ProductNotfoundException.class) public ResponseEntity<Object> exception(ProductNotfoundException exception) { }
現在,使用以下程式碼從 API 中丟擲異常。
@PutMapping(value = "/products/{id}") public ResponseEntity<Object> updateProduct() { throw new ProductNotfoundException(); }
處理異常的完整程式碼如下所示。在這個例子中,我們使用 PUT API 來更新產品。在這裡,如果在更新產品時找不到產品,則返回錯誤訊息“產品未找到”。請注意,**ProductNotFoundException** 異常類應該擴充套件 **RuntimeException**。
ProductNotfoundException.java
package com.tutorialspoint.demo.exception; public class ProductNotfoundException extends RuntimeException { private static final long serialVersionUID = 1L; }
全域性處理異常的 Controller Advice 類如下所示。我們可以在此類檔案中定義任何異常處理器方法。
ProductExceptionController
package com.tutorialspoint.demo.exception; 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 ProductExceptionController { @ExceptionHandler(value = ProductNotfoundException.class) public ResponseEntity<Object> exception(ProductNotfoundException exception) { return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND); } }
用於更新產品的 Product Service API 控制器檔案如下所示。如果找不到產品,則會丟擲 **ProductNotFoundException** 類。
ProductServiceController.java
package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.exception.ProductNotfoundException; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId("1"); honey.setName("Honey"); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId("2"); almond.setName("Almond"); productRepo.put(almond.getId(), almond); } @PutMapping(value = "/products/{id}") public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Product product) { if(!productRepo.containsKey(id))throw new ProductNotfoundException(); productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>("Product is updated successfully", HttpStatus.OK); } }
Spring Boot 主應用程式類檔案的程式碼如下:
DemoApplication.java
package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
產品的 **POJO 類** 程式碼如下:
Product.java
package com.tutorialspoint.demo.model; public class Product { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
**Maven 構建 – pom.xml** 程式碼如下:
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.tutorialspoint</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>21</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
**Gradle 構建 – build.gradle** 程式碼如下:
build.gradle
buildscript { ext { springBootVersion = '3.3.3' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.tutorialspoint' version = '0.0.1-SNAPSHOT' sourceCompatibility = 21 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') }
您可以建立一個可執行的 JAR 檔案,並使用 Maven 或 Gradle 命令執行 Spring Boot 應用程式:
對於 Maven,您可以使用以下命令:
mvn clean install
“BUILD SUCCESS”之後,您可以在 target 目錄下找到 JAR 檔案。
對於 Gradle,您可以使用以下命令:
gradle clean build
“BUILD SUCCESSFUL”之後,您可以在 build/libs 目錄下找到 JAR 檔案。
您可以使用以下命令執行 JAR 檔案:
java –jar <JARFILE>
這將在 Tomcat 埠 8080 上啟動應用程式,如下所示:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ [32m :: Spring Boot :: [39m [2m (v3.3.3)[0;39m [2024-09-05T11:10:46Z] [org.springframework.boot.StartupInfoLogger] [main] [50] [INFO ] Starting DemoApplication using Java 21.0.3 with PID 8820 (E:\Dev\demo\target\classes started by Tutorialspoint in E:\Dev\demo) [2024-09-05T11:10:46Z] [org.springframework.boot.SpringApplication] [main] [654] [INFO ] No active profile set, falling back to 1 default profile: "default" [2024-09-05T11:10:48Z] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] [main] [111] [INFO ] Tomcat initialized with port 8080 (http) [2024-09-05T11:10:48Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Initializing ProtocolHandler ["http-nio-8080"] [2024-09-05T11:10:48Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting service [Tomcat] [2024-09-05T11:10:48Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting Servlet engine: [Apache Tomcat/10.1.28] [2024-09-05T11:10:48Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Initializing Spring embedded WebApplicationContext [2024-09-05T11:10:48Z] [org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext] [main] [296] [INFO ] Root WebApplicationContext: initialization completed in 1648 ms [2024-09-05T11:10:49Z] [org.apache.juli.logging.DirectJDKLog] [main] [173] [INFO ] Starting ProtocolHandler ["http-nio-8080"] [2024-09-05T11:10:49Z] [org.springframework.boot.web.embedded.tomcat.TomcatWebServer] [main] [243] [INFO ] Tomcat started on port 8080 (http) with context path '/' [2024-09-05T11:10:49Z] [org.springframework.boot.StartupInfoLogger] [main] [56] [INFO ] Started DemoApplication in 3.242 seconds (process running for 4.776)
現在在 POSTMAN 應用程式中點選以下 URL,您可以看到如下所示的輸出:
更新 URL:https://:8080/products/3
