Spring Boot 實現(xiàn)異常統(tǒng)一處理
一、引言
在開發(fā)基于 Spring Boot 的應(yīng)用程序時,異常處理是一個不可忽視的重要環(huán)節(jié)。良好的異常處理機制可以提高系統(tǒng)的健壯性和可維護性,同時為用戶和開發(fā)者提供更友好的錯誤反饋。在傳統(tǒng)的開發(fā)中,我們可能會在每個控制器方法中編寫大量的異常處理代碼,這樣會導(dǎo)致代碼冗余且難以維護。Spring Boot 提供了強大的異常統(tǒng)一處理機制,通過使用注解和特定的類,我們可以將異常處理邏輯集中管理,避免代碼重復(fù),提高開發(fā)效率。
二、Spring Boot 異常處理基礎(chǔ)
在 Spring Boot 中,異常處理主要基于兩個核心概念:@ControllerAdvice 和 @ExceptionHandler。
2.1 @ControllerAdvice
@ControllerAdvice 是一個特殊的 @Component,用于定義 @ExceptionHandler、@InitBinder 和 @ModelAttribute 方法,這些方法將應(yīng)用到所有使用 @RequestMapping 注解的控制器類中的方法。簡單來說,@ControllerAdvice 是一個全局的異常處理類,它可以捕獲所有控制器中拋出的異常。
2.2 @ExceptionHandler
@ExceptionHandler 注解用于指定處理特定異常的方法。當(dāng)控制器方法拋出指定類型的異常時,Spring Boot 會自動調(diào)用被 @ExceptionHandler 注解標(biāo)注的方法來處理該異常。
三、實現(xiàn)異常統(tǒng)一處理的步驟
3.1 創(chuàng)建自定義異常類
首先,我們可以創(chuàng)建自定義異常類,以便在業(yè)務(wù)邏輯中拋出特定類型的異常。例如:
public class CustomException extends RuntimeException {
private int code;
private String message;
public CustomException(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
}
3.2 創(chuàng)建全局異常處理類
使用 @ControllerAdvice 和 @ExceptionHandler 注解創(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 {
@ExceptionHandler(CustomException.class)
public ResponseEntity<String> handleCustomException(CustomException ex) {
return new ResponseEntity<>("Custom Exception: Code - " + ex.getCode() + ", Message - " + ex.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneralException(Exception ex) {
return new ResponseEntity<>("General Exception: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
在上述代碼中,GlobalExceptionHandler 類使用 @ControllerAdvice 注解,表明它是一個全局異常處理類。handleCustomException 方法使用 @ExceptionHandler 注解,專門處理 CustomException 類型的異常,返回一個包含異常信息的 ResponseEntity 對象,狀態(tài)碼為 400 Bad Request。handleGeneralException 方法處理所有其他類型的異常,返回一個包含異常信息的 ResponseEntity 對象,狀態(tài)碼為 500 Internal Server Error。
3.3 在控制器中拋出異常
創(chuàng)建一個簡單的控制器,在其中拋出異常:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/test")
public String test() {
throw new CustomException(1001, "This is a custom exception");
}
}
當(dāng)訪問 /test 接口時,控制器方法會拋出 CustomException 異常,該異常會被 GlobalExceptionHandler 類中的 handleCustomException 方法捕獲并處理。
四、返回統(tǒng)一的錯誤響應(yīng)格式
為了讓前端更容易處理錯誤信息,我們可以定義一個統(tǒng)一的錯誤響應(yīng)格式。
4.1 創(chuàng)建錯誤響應(yīng)類
public class ErrorResponse {
private int code;
private String message;
public ErrorResponse(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
4.2 修改全局異常處理類
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(CustomException.class)
public ResponseEntity<ErrorResponse> handleCustomException(CustomException ex) {
ErrorResponse errorResponse = new ErrorResponse(ex.getCode(), ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGeneralException(Exception ex) {
ErrorResponse errorResponse = new ErrorResponse(500, ex.getMessage());
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
現(xiàn)在,異常處理方法返回的是包含 ErrorResponse 對象的 ResponseEntity,前端可以根據(jù) ErrorResponse 中的 code 和 message 字段來處理錯誤信息。
五、總結(jié)
通過使用 @ControllerAdvice 和 @ExceptionHandler 注解,我們可以在 Spring Boot 中實現(xiàn)異常的統(tǒng)一處理。這種方式將異常處理邏輯集中管理,避免了代碼冗余,提高了系統(tǒng)的可維護性。同時,定義統(tǒng)一的錯誤響應(yīng)格式可以讓前端更容易處理錯誤信息,提升用戶體驗。在實際開發(fā)中,我們可以根據(jù)業(yè)務(wù)需求創(chuàng)建更多的自定義異常類,并在全局異常處理類中添加相應(yīng)的處理方法。