이전 글에 다루었던 Validation 라이브러리 편을 먼저 보시는 것을 권장합니다.
https://getthismoment.tistory.com/84
validation과 함께 사용해야하는 exception 예외 처리에 관해서 알아봅시다.
Spring boot에 내장되어있는 라이브러리 중에 예외처리를 손쉽게 도와주는 라이브러리가 있습니다.
try/catch 나 throw exception 형식으로 주로 예외처리를 하지만, exception 라이브러리는 상황에 따라서 특정값을 예외처리하거나 사용자 정의에 의해서 예외처리를 하고 싶은 경우 유용하게 사용할 수 있습니다.
전역 예외 처리 @RestControllerAdvice
@RestControllerAdvice
public class GlobalControllerAdvice {
@ExceptionHandler(value = Exception.class)
public ResponseEntity exception(Exception e) {
System.out.println(e.getClass().getName());
System.out.println("------------------------------");
System.out.println(e.getLocalizedMessage());
System.out.println("------------------------------");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("");
}
}
다음 예제와 같이 일반적으로 전체 controller에 예외를 일괄적용할 수 있습니다.
특정 컨트롤러에만 예외를 적용하고 싶다면, @RestControllerAdvice의 속성에 값을 주면 됩니다.
@RestControllerAdvice(basePackages = "com.example.project.controller", basePackageClasses = { TestController1.class, TestController2.class})
basePackages 속성에 예외를 적용할 컨트롤러 패키지 경로를 basePackageClasses 속성에 컨트롤러 클래스를 기술하면 됩니다. 두 속성 중 하나만 적용하셔도 됩니다.
그외 assignableTypesd와 annotations 속성을 이용해서 메소드 단위나 어노테이션 단위에도 적용할 수 있습니다.
자세한건 다른 참고 자료를 찾아보시길 바랍니다.
https://jjhwqqq.tistory.com/138
ControllerAdvice
특정 범위에 포함된 모든 Controller에서 발생하는 Exception을 전역처리할 때 ControllerAdvice를 사용한다. import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; import org.sprin..
jjhwqqq.tistory.com
System.out.println(e.getClass().getName()); 메소드를 출력해서 exception 명을 쉽게 찾을 수 있습니다.
@RestControllerAdvice
public class GlobalControllerAdvice {
...
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResponseEntity methodArgumentNotValidException(MethodArgumentNotValidException e) {
System.out.println("advice 클래스");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}
exception 명을 얻어서 @ExceptionHandler(value = "")의 value 속성에 exception 명을 기술하여, 손쉽게 예외처리 메소드를 만들 수 있습니다.
특정 컨트롤러에서 예외 처리
// ApiController.java
@RestController
@RequestMapping("/api")
public class ApiController {
...
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResponseEntity methodArgumentNotValidException(MethodArgumentNotValidException e) {
System.out.println("apiController");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}
예외 처리를 하고 싶은 타겟 컨트롤러에 @ExceptionHandler 어노테이션을 적용한 메소드를 만들어 주시면 됩니다.
@RestControllerAdvice 어노테이션을 붙이면 global로 예외를 처리할 수 있지만, 특정 controller에서 예외 처리를 하여 예외 처리 범위를 지정할 수 있습니다.
global 예외처리와 controller 예외 처리가 중복된다면, controller 예외처리를 우선적으로 실행되며 global 예외처리는 실행되지 않습니다.
Exception 예제를 활용한 심화 내용은 다음 링크를 통해서 확인할 수 있습니다.
https://getthismoment.tistory.com/87?category=1009632
'Spring Boot' 카테고리의 다른 글
Spring Boot - Exception 구현 예제 (0) | 2021.09.13 |
---|---|
Spring Boot - Filter (0) | 2021.09.12 |
Spring Boot - Validation (0) | 2021.09.09 |
Spring Boot - Annotation 참고자료 (0) | 2021.09.07 |
Spring Boot - AOP (Aspect Oriented Programming) (0) | 2021.09.03 |
댓글