@ExceptionHandler
`@ExceptionHandler`는 특정 예외가 발생했을 때 해당 예외를 처리하는 메서드를 정의할 수 있습니다.
`@ExceptionHandler`는 적용 범위 제한이 있는데, `@Contoller`, `@RestController`, `@ControllerAdvice`에서 사용이 가능합니다. 컨트롤러가 적용된 Bean에서 발생하는 예외를 잡고 해당 예외가 설정된 `@ExceptionHandler`가 적용된 메서드가 실행됩니다.
@Controller
public class demoController {
//...
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleException(Exception ex) {
// ...
}
}
`@ExceptionHandler(Exception.class)`는 `Exception`클래스로부터 파생된 예외가 발생했을 때 해당 메서드가 실행되도록 설정한 것입니다. 즉, demoController에서 작업 중 `Exception`이 발생하면 `@ExceptionHandler(Exception.class`)를 적용한 메서드가 동작하게 됩니다.
예외 처리 메서드는 일반적으로 `ResponseEntity`를 반환하여 응답합니다. 응답은 예외에 따라 상태 코드, 에러 메시지, 추가 정보 등을 갖고 있을 수 있습니다.
`@ExceptionHandler`는 등록된 Controller 내에서만 적용되기 때문에 다른 Controller에서도 같은 처리를 해주기 위해서는 `@ExceptionHandler`를 똑같이 다른 Controller 에도 적용해주어야 합니다. 이는 번거로운 작업이기 때문에 `@ExceptionHandler` 어노테이션을 `@ControllerAdvice` 어노테이션과 함께 사용해서 전역적인 예외 처리를 구현할 수 있습니다.
@ControllerAdvice
`@ControllerAdvice`이 붙은 클래스는 모든 컨트롤러에서 발생하는 예외를 잡을 수 있습니다.
때문에 `@ControllerAdvice`가 적용된 클래스에서 `@ExceptionHandler`를 적용한다면 모든 컨트롤러에서 발생하는 예외 상황을 잡을 수 있습니다.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(CustomException.class)
public ResponseEntity<Object> handleException(Exception ex) {
// ...
}
@ExceptionHandler(SQLException.class)
public ResponseEntity<Object> handleException(Exception ex) {
// ...
}
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<Object> handleException(Exception ex) {
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
'Spring Framework' 카테고리의 다른 글
Spring @RequestParam/@PathVariable/@RequestBody/@RequestHeader/@CookieValue (0) | 2023.05.25 |
---|---|
Spring web.xml, root-context.xml, servlet-context.xml (0) | 2023.05.23 |
로그인 처리를 위한 UserDetailsService (0) | 2022.10.14 |
Spring Thymeleaf 살펴보기 (0) | 2022.10.06 |
Spring ResponseEntity (0) | 2022.09.21 |