만쥬의 개발일기
article thumbnail

개발을 하다보면 예외처리는 필수 불가결 적이다. 그리고 예외처리는 한 곳에서만 하는 것이 아닌, 내 코드 모든 곳에서 발생하는 AOP이다. 따라서 공통적으로 처리해야만 하는데, 이를 도와주는 어노테이션이 있다.

 

@ControllerAdvice vs @RestControllerAdvice

@ControllerAdvice란 @ExceptionHandler, @ModelAttribute, @InitBinder 가 적용된 메서드들을 AOP를 적용해 컨트롤러 단에 적용하기 위해 고안된 어노테이션이다.

 

클래스에 선언하게 되면, 모든 @Controller에 대한 전역적으로 발생하는 예외를 처리 가능하다.

또한 내부적으로 @Component가 선언되어 있어 빈으로 관리된다.

 

@RestControllerAdvice란 @ControllerAdvice에 @ResponseBody를 추가한 형태이다.

@ResponseBody를 통해 객체를 리턴할 수도 있다.

단순히 예외만 처리한다면 @ControllerAdvice를 적용하고, 응답으로 객체를 리턴하고 싶다면 @RestControllerAdvice를 적용하면 된다.

 

적용 범위는 클래스 또는 패키지 단위로 제한할 수도 있다.

 

 

사용 방법

@RestControllerAdvice(annotations = RestController.class)
public class HelloControllerAdvice {

	@ExceptionHandler
	public String errorHandler(HelloException e) {
		return e.getMessage();
	}
}

@ControllerAdvice 또는 @RestControllerAdvice가 선언된 클래스 내부의 메서드에 위와 같이 어노테이션을 선언하고 처리할 예외 타입을 선언해주기만 하면 된다. 그러면 알아서 해당 예외를 erroHandler() 메서드에 정의된 로직으로 처리할 수 있게 되고, 원하는 객체를 반환할 수도 있다. ( ex) responseEntity)

 

	@ExceptionHandler(value = {HelloException.class, NoSuchElementException.class})
	public String errorHandler(RuntimeException e) {
		return e.getMessage();
	}

 

만약 위와 같이 value 값을 지정하고, 둘의 공통 타입인 RuntimeException을 파라미터로 지정하면, HelloException과 NosuchElementException을 각각 메서드로 만들지 않아도, 해당 함수에서 한번에 처리가 가능하다.

 

reference

profile

만쥬의 개발일기

@KangManJoo

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!