SpringBoot 如何使用 @ControllerAdvice 注解進行全局異常處理
在 Web 開發(fā)中,異常處理是非常重要的一環(huán)。在 SpringBoot 框架中,我們通常使用 @ExceptionHandler 注解來處理 Controller 層的異常。但是,如果想要處理全局異常,我們需要使用 @ControllerAdvice 注解。本文將介紹如何在 SpringBoot 中使用 @ControllerAdvice 注解進行全局異常處理。
什么是 @ControllerAdvice
@ControllerAdvice 注解是 Spring Framework 3.2 引入的一個新特性,它用于定義全局異常處理器。使用 @ControllerAdvice 注解,我們可以集中處理所有 Controller 層拋出的異常,而不必在每個 Controller 中單獨處理。
@ControllerAdvice 注解通常與 @ExceptionHandler 注解一起使用,@ExceptionHandler 注解用于定義具體的異常處理方法,@ControllerAdvice 注解用于定義全局異常處理器。
如何使用 @ControllerAdvice 進行全局異常處理
使用 @ControllerAdvice 進行全局異常處理的步驟如下:
- 創(chuàng)建一個全局異常處理類
我們可以創(chuàng)建一個類并使用 @ControllerAdvice 注解進行標注,例如:
@ControllerAdvice
public class GlobalExceptionHandler {
// 異常處理方法
}
在上述代碼中,我們使用 @ControllerAdvice 注解標注了一個類,并命名為 GlobalExceptionHandler。接下來,我們可以在 GlobalExceptionHandler 類中定義具體的異常處理方法。
- 定義異常處理方法
在 GlobalExceptionHandler 類中定義具體的異常處理方法,例如:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
在上述代碼中,我們使用 @ExceptionHandler 注解定義了一個處理 Exception 類型異常的方法,并返回一個 ResponseEntity 對象。在處理方法中,我們可以根據(jù)具體的業(yè)務(wù)需求對異常進行相應(yīng)的處理,并返回相應(yīng)的結(jié)果。
- 處理其他類型的異常
除了處理 Exception 類型的異常外,我們還可以根據(jù)具體的業(yè)務(wù)需求,處理其他類型的異常。例如,如果我們想要處理參數(shù)校驗失敗的異常,可以在 GlobalExceptionHandler 類中定義一個處理 MethodArgumentNotValidException 類型異常的方法。
@ControllerAdvice
public class GlobalExceptionHandler {
// 處理 Exception 類型異常的方法
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
List<ObjectError> allErrors = bindingResult.getAllErrors();
List<String> errorMessages = new ArrayList<>();
for (ObjectError error : allErrors) {
errorMessages.add(error.getDefaultMessage());
}
String errorMessage = String.join(",", errorMessages);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMessage);
}
}
在上述代碼中,我們使用 @ExceptionHandler 注解定義了一個處理 MethodArgumentNotValidException 類型異常的方法。在處理方法中,我們首先獲取 BindingResult 對象,并遍歷其中的所有錯誤信息,將它們合并為一個錯誤消息,并返回一個 ResponseEntity 對象。
完整代碼示例
下面是一個完整的使用 @ControllerAdvice 進行全局異常處理的示例代碼:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
List<ObjectError> allErrors = bindingResult.getAllErrors();
List<String> errorMessages = new ArrayList<>();
for (ObjectError error : allErrors) {
errorMessages.add(error.getDefaultMessage());
}
String errorMessage = String.join(",", errorMessages);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMessage);
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/add")
public Result addUser(@Validated @RequestBody User user) {
// 處理添加用戶的邏輯
}
}
@Data
public class User {
@NotNull(message = "用戶名不能為空")
private String username;
@NotNull(message = "密碼不能為空")
@Size(min = 6, message ="密碼長度不能小于6")
private String password;
}
在上述代碼中,我們定義了一個 GlobalExceptionHandler 類,使用 @ControllerAdvice 注解標注,并在其中定義了處理 Exception 和 MethodArgumentNotValidException 類型異常的方法。
我們還定義了一個 UserController 類,并在其中定義了一個添加用戶的接口。在添加用戶接口中,我們使用 @Validated 注解對 User 對象進行參數(shù)校驗,并在 User 類中使用了 javax.validation.constraints 包中的注解對 username 和 password 屬性進行了校驗。如果參數(shù)校驗失敗,會觸發(fā) MethodArgumentNotValidException 異常,在 GlobalExceptionHandler 類中的 handleMethodArgumentNotValidException 方法中進行處理。文章來源:http://www.zghlxwxcb.cn/news/detail-498319.html
總結(jié)
在本文中,我們介紹了如何在 SpringBoot 中使用 @ControllerAdvice 注解進行全局異常處理。通過使用 @ControllerAdvice 注解,我們可以集中處理所有 Controller 層拋出的異常,而不必在每個 Controller 中單獨處理。在 GlobalExceptionHandler 類中定義異常處理方法,并根據(jù)具體的業(yè)務(wù)需求對異常進行相應(yīng)的處理,可以大大提高代碼的可維護性和可讀性。文章來源地址http://www.zghlxwxcb.cn/news/detail-498319.html
到了這里,關(guān)于SpringBoot 如何使用 @ControllerAdvice 注解進行全局異常處理的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!