全局異常處理器
當(dāng)存在很多自定義異常類時(shí),編寫全局異常處理器需要系統(tǒng)性地對(duì)不同類型的異常進(jìn)行分類處理,以保證代碼的清晰性和可維護(hù)性。下面為你詳細(xì)介紹實(shí)現(xiàn)方法和示例代碼。
實(shí)現(xiàn)思路
- 定義自定義異常類:為不同的業(yè)務(wù)場景創(chuàng)建對(duì)應(yīng)的自定義異常類,這些類通常繼承自
RuntimeException
或其他合適的異常類。 - 創(chuàng)建全局異常處理器類:使用
@ControllerAdvice
注解標(biāo)記一個(gè)類作為全局異常處理器,在該類中使用@ExceptionHandler
注解來定義處理不同異常類型的方法。 - 分類處理異常:根據(jù)異常的類型和業(yè)務(wù)需求,為不同的自定義異常類編寫專門的處理方法,同時(shí)提供一個(gè)通用的異常處理方法來處理未被明確捕獲的異常。
示例代碼
1. 定義多個(gè)自定義異常類
// 業(yè)務(wù)異?;?public class BusinessException extends RuntimeException {
public BusinessException(String message) {
super(message);
}
}
// 用戶相關(guān)業(yè)務(wù)異常
public class UserException extends BusinessException {
public UserException(String message) {
super(message);
}
}
// 訂單相關(guān)業(yè)務(wù)異常
public class OrderException extends BusinessException {
public OrderException(String message) {
super(message);
}
}
2. 創(chuàng)建全局異常處理器類
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 {
// 處理用戶相關(guān)業(yè)務(wù)異常
@ExceptionHandler(UserException.class)
public ResponseEntity<String> handleUserException(UserException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
// 處理訂單相關(guān)業(yè)務(wù)異常
@ExceptionHandler(OrderException.class)
public ResponseEntity<String> handleOrderException(OrderException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT);
}
// 處理其他業(yè)務(wù)異常
@ExceptionHandler(BusinessException.class)
public ResponseEntity<String> handleBusinessException(BusinessException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
// 處理其他未被捕獲的異常
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneralException(Exception e) {
return new ResponseEntity<>("An unexpected error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
3. 業(yè)務(wù)代碼中拋出異常
import org.springframework.stereotype.Service;
@Service
public class UserService {
public void validateUser(String username) {
if (username == null || username.isEmpty()) {
throw new UserException("Username cannot be empty");
}
// 其他業(yè)務(wù)邏輯
}
}
@Service
public class OrderService {
public void createOrder() {
// 模擬訂單創(chuàng)建失敗
throw new OrderException("Order creation failed due to insufficient stock");
}
}
4. 控制器調(diào)用業(yè)務(wù)方法
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@Autowired
private OrderService orderService;
@GetMapping("/validateUser")
public String validateUser(@RequestParam String username) {
userService.validateUser(username);
return "User validation passed";
}
@GetMapping("/createOrder")
public String createOrder() {
orderService.createOrder();
return "Order created successfully";
}
}
代碼解釋
- 自定義異常類:
BusinessException
作為業(yè)務(wù)異常的基類,UserException
和OrderException
繼承自BusinessException
,用于區(qū)分不同業(yè)務(wù)場景下的異常。 - 全局異常處理器:
GlobalExceptionHandler
類使用@ControllerAdvice
注解,其中每個(gè)@ExceptionHandler
注解的方法負(fù)責(zé)處理特定類型的異常。對(duì)于不同的自定義異常類,返回不同的 HTTP 狀態(tài)碼和錯(cuò)誤信息。 - 業(yè)務(wù)代碼:在
UserService
和OrderService
中,根據(jù)業(yè)務(wù)邏輯拋出相應(yīng)的自定義異常。 - 控制器:
UserController
調(diào)用業(yè)務(wù)方法,當(dāng)業(yè)務(wù)方法拋出異常時(shí),全局異常處理器會(huì)自動(dòng)捕獲并處理。
通過上述方法,你可以清晰地對(duì)多個(gè)自定義異常類進(jìn)行分類處理,提高代碼的可維護(hù)性和可讀性。
Spring 文章被收錄于專欄
Spring 生態(tài)是以 Spring Framework 為核心,衍生出的一系列相互關(guān)聯(lián)、功能互補(bǔ)的技術(shù)和工具集合,用于簡化企業(yè)級(jí)應(yīng)用開發(fā),覆蓋從單體應(yīng)用到分布式微服務(wù)、從 Web 開發(fā)到數(shù)據(jù)處理等諸多場景。