我想在 Spring 中正確處理我的例外,所以我有一個關于 exceptionHandler 語法的問題:如果它們被例外處理程式捕獲,是否可以在控制器中拋出特定例外?
進一步來說 :
這是例外:
public class UnknownUserException extends Exception {
private static final long serialVersionUID = 1L;
public UnknownUserException(String message) {
super(message);
}
}
這是具有 UnknownUserException 特定方法的 ExceptionHandler :
@ControllerAdvice
@ResponseBody
public class ControllerExceptionHandler {
@ExceptionHandler(UnknownUserException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ErrorMessage unknownUserExceptionMessage(UnknownUserException ex, WebRequest request) {
ErrorMessage message = new ErrorMessage("The user doesn't exist: " ex.getLocalizedMessage(), ex);
return message;
}
}
以下是可能引發該例外的映射示例:
@GetMapping({"/user/{id}"})
public ResponseEntity<UserProfileDto> getById(@PathVariable Long id) throws UnknownUserException {
UserProfileDto user = userService.findById(id);
return ResponseEntity.ok(user);
}
userService.findById(id) 可能會拋出 UnknownUserException。
據我所知,如果服務拋出特定例外,controllerAdvice 會“覆寫”控制器,但是,我應該如何處理我的控制器?我應該再次拋出例外(如上)還是捕獲特定例外并回傳 ResponseEntity(HttpStatus.NOT_FOUND) ?
uj5u.com熱心網友回復:
在理想情況下,例外應該在您的情況下已知時立即拋出UnknownUserException,因為您提到服務方法將拋出正確的事情。您的 Controller Advice 應該能夠處理該例外。ContollerAdvice將處理在執行請求期間拋出的任何匹配例外,而不管例外的來源。
有關處理例外的其他選項,請參閱此鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314152.html
