關于SpringBoot使用@ExceptionHandler注解局部異常處理
介紹
在開發(fā) Web 應用程序時,異常處理是非常重要的一部分。SpringBoot 提供了多種方式來處理異常,其中之一是使用 @ExceptionHandler 注解進行局部異常處理。使用 @ExceptionHandler 注解,我們可以在 Controller 層或方法級別上處理異常,而不用在整個應用程序中處理。
@ExceptionHandler 注解
@ExceptionHandler 注解是 SpringFramework 提供的一個注解,用于處理控制器中出現的異常。當在控制器方法中拋出異常時,SpringBoot 會查找?guī)в?@ExceptionHandler 注解的方法,并調用它來處理異常。
下面是一個簡單的例子:
@RestController public class UserController { @GetMapping("/users/{id}") public User getUser(@PathVariable int id) { User user = userRepository.findById(id); if (user == null) { throw new UserNotFoundException("User not found"); } return user; } @ExceptionHandler(UserNotFoundException.class) public ResponseEntity<ErrorResponse> handleUserNotFoundException(UserNotFoundException ex) { ErrorResponse error = new ErrorResponse(HttpStatus.NOT_FOUND.value(), ex.getMessage()); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } }
在上面的代碼中,我們定義了一個 UserController 類,并實現了一個 getUser 方法。如果用戶不存在,則拋出 UserNotFoundException 異常。然后,我們使用 @ExceptionHandler 注解定義了一個 handleUserNotFoundException 方法,用于處理 UserNotFoundException 異常。在該方法中,我們創(chuàng)建了一個 ErrorResponse 對象,包含了錯誤響應的狀態(tài)碼和消息,然后將其封裝在 ResponseEntity 對象中返回。
如何使用 @ExceptionHandler 注解進行局部異常處理
要使用 @ExceptionHandler 注解進行局部異常處理,請按照以下步驟操作:
第 1 步:定義自定義異常
在代碼中定義自定義異常,繼承自 Exception 或 RuntimeException 類。例如:
public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } }
在上面的代碼中,我們定義了一個名為 UserNotFoundException 的自定義異常,它繼承自 RuntimeException 類。
第 2 步:拋出異常
在控制器方法中拋出自定義異常。例如:
@GetMapping("/users/{id}") public User getUser(@PathVariable int id) { User user = userRepository.findById(id); if (user == null) { throw new UserNotFoundException("User not found"); } return user; }
在上面的代碼中,如果用戶不存在,則拋出 UserNotFoundException 異常。
第 3 步:處理異常
使用 @ExceptionHandler 注解定義一個方法,用于處理自定義異常。例如:
@ExceptionHandler(UserNotFoundException.class) public ResponseEntity<ErrorResponse> handleUserNotFoundException(UserNotFoundException ex) { ErrorResponse error = new ErrorResponse(HttpStatus.NOT_FOUND.value(), ex.getMessage()); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); }
在上面的代碼中,我們使用 @ExceptionHandler(UserNotFoundException.class) 注解定義了一個方法 handleUserNotFoundException,用于處理 UserNotFoundException 異常。在該方法中,我們創(chuàng)建了一個 ErrorResponse 對象,包含了錯誤響應的狀態(tài)碼和消息,然后將其封裝在 ResponseEntity 對象中返回。
示例
以下是一個完整的示例:
UserController.java
@RestController public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/users/{id}") public User getUser(@PathVariable int id) { User user = userRepository.findById(id); if (user == null) { throw new UserNotFoundException("User not found"); } return user; } @PostMapping("/users") public User createUser(@RequestBody User user) { userRepository.save(user); return user; } @PutMapping("/users/{id}") public User updateUser(@PathVariable int id, @RequestBody User user) { User existingUser = userRepository.findById(id); if (existingUser == null) { throw new UserNotFoundException("User not found"); } existingUser.setName(user.getName()); existingUser.setAge(user.getAge()); userRepository.save(existingUser); return existingUser; } @DeleteMapping("/users/{id}") public void deleteUser(@PathVariable int id) { UseruserRepository.deleteById(id); } @ExceptionHandler(UserNotFoundException.class) public ResponseEntity<ErrorResponse> handleUserNotFoundException(UserNotFoundException ex) { ErrorResponse error = new ErrorResponse(HttpStatus.NOT_FOUND.value(), ex.getMessage()); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } }
UserNotFoundException.java
public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } }
ErrorResponse.java
public class ErrorResponse { private int status; private String message; public ErrorResponse(int status, String message) { this.status = status; this.message = message; } public int getStatus() { return status; } public String getMessage() { return message; } }
在上面的代碼中,我們定義了一個 UserController 類,實現了 getUser、createUser、updateUser 和 deleteUser 方法。如果用戶不存在,則拋出 UserNotFoundException 異常。然后,我們使用 @ExceptionHandler 注解定義了一個 handleUserNotFoundException 方法,用于處理 UserNotFoundException 異常。在該方法中,我們創(chuàng)建了一個 ErrorResponse 對象,包含了錯誤響應的狀態(tài)碼和消息,然后將其封裝在 ResponseEntity 對象中返回。
原理
當控制器方法拋出異常時,SpringBoot 會在控制器類中查找?guī)в?@ExceptionHandler 注解的方法,并調用它來處理異常。@ExceptionHandler 注解的方法必須具有以下特征:
- 方法必須是 public、沒有返回值,并且具有一個參數,該參數類型為拋出的異常類型。
- 方法必須使用 @ExceptionHandler 注解進行注解,該注解的參數為拋出的異常類型。
當控制器方法拋出異常時,SpringBoot 將異常傳遞給帶有 @ExceptionHandler 注解的方法。該方法將處理異常,并返回一個 ResponseEntity 對象,該對象包含錯誤響應的狀態(tài)碼和消息。
總結
在本文中,我們介紹了 SpringBoot 中的 @ExceptionHandler 注解,演示了如何使用它進行局部異常處理。使用 @ExceptionHandler 注解,我們可以在 Controller 層或方法級別上處理異常。當控制器方法拋出異常時,SpringBoot 會查找?guī)в?@ExceptionHandler 注解的方法,并調用它來處理異常。要使用 @ExceptionHandler 注解進行局部異常處理,需要定義自定義異常、拋出異常和處理異常。
到此這篇關于關于SpringBoot使用@ExceptionHandler注解局部異常處理的文章就介紹到這了,更多相關@ExceptionHandler局部異常處理內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Spring中的@ExceptionHandler注解統(tǒng)一異常處理詳解
- SpringMVC使用@ExceptionHandler注解在Controller中處理異常
- Spring的異常處理@ExceptionHandler注解解析
- Spring中@ExceptionHandler注解的使用方式
- Spring中@ExceptionHandler注解的工作原理詳解
- Spring @ExceptionHandler注解統(tǒng)一異常處理和獲取方法名
- Spring中的@ControllerAdvice和@ExceptionHandler注解處理全局異常
- Spring中的@ExceptionHandler注解詳解與應用示例
相關文章
SpringBoot @value注解動態(tài)刷新問題小結
@Value注解 所對應的數據源來自項目的 Environment 中,我們可以將數據庫或其他文件中的數據,加載到項目的 Environment 中,然后 @Value注解 就可以動態(tài)獲取到配置信息了,這篇文章主要介紹了SpringBoot @value注解動態(tài)刷新,需要的朋友可以參考下2023-09-09