'@ControllerAdvice @ExceptionHandler'에 해당되는 글 1건

  1. 2022.04.12 @RestControllerAdvice 관련 정리

@ControllerAdvice+@ResponseBody 를 한꺼번에 사용 할 수 있게 해주는 어노테이션 입니다.

 

@ControllerAdvice은 @InitBinder, @ModelAttribute, @ExceptionHandler 관련 어노테이션을 여러 컨트롤러에 걸쳐 공통으로 설정 할 수 있게 해주는 어노테이션 인데 ExceptionHandler를 위해서 많이 사용 하고 있습니다.

 

@ControllerAdvice(assignableTypes={TestController.class, Test2Controller.class})

와 같이 사용해서 영향을 미치는 컨트롤러를 정의 할 수 있고 범위는 class, 패키지, 특정 어노테이션 등으로 정의 할 수 있습니다.

assignableTypes의 조건을 많이 사용하는 경우 성능에 악영향을 미칠 수 있습니다.

https://docs.spring.io/spring-framework/docs/5.3.18/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html

 

ControllerAdvice (Spring Framework 5.3.18 API)

Specialization of @Component for classes that declare @ExceptionHandler, @InitBinder, or @ModelAttribute methods to be shared across multiple @Controller classes. Classes annotated with @ControllerAdvice can be declared explicitly as Spring beans or auto-d

docs.spring.io

ExceptionHandler 와 같이 사용하는 경우 아래와 같이 사용 할 수 있습니다.

@RestControllerAdvice
public class ControllerExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@ResponseStatus(value = HttpStatus.OK)
	@ExceptionHandler(value = NullPointerException.class)
    public HashMap<String, Object> nullPointerException(Exception e, Model model) {
		
		logger.error(e.getLocalizedMessage());
		
		HashMap<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("result", false);
		returnMap.put("message", "비정상적인 정보(null) 입니다.");
		
        return returnMap;
    }
    
    @ResponseStatus(value = HttpStatus.OK)
	@ExceptionHandler(value = ClassCastException.class)
    public HashMap<String, Object> classCastException(Exception e, Model model) {
		
		logger.error(e.getLocalizedMessage());
		
		HashMap<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("result", false);
		returnMap.put("message", "프로그램이 비정상 구동 되었습니다. 시스템 확인이 필요 합니다.(classCastException)");
		
        return returnMap;
    }
    
    @ResponseStatus(value = HttpStatus.OK)
   	@ExceptionHandler(value = NoClassDefFoundError.class)
       public HashMap<String, Object> noClassDefFoundError(Exception e, Model model) {
   		
   		logger.error(e.getLocalizedMessage());
   		
   		HashMap<String, Object> returnMap = new HashMap<String, Object>();
   		returnMap.put("result", false);
   		returnMap.put("message", "프로그램이 비정상 구동 되었습니다. 시스템 확인이 필요 합니다.(noClassDefFoundError)");
   		
           return returnMap;
       }
	
	@ResponseStatus(value = HttpStatus.OK)
	@ExceptionHandler(value = ArrayIndexOutOfBoundsException.class)
    public HashMap<String, Object> arrayIndexOutOfBoundsException(Exception e, Model model) {
		
		logger.error(e.getLocalizedMessage());
		
		HashMap<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("result", false);
		returnMap.put("message", "비정상적인 배열 정보 입니다.(ArrayIndexOutOfBoundsException)");
		
        return returnMap;
    }
	
	@ResponseStatus(value = HttpStatus.OK)
	@ExceptionHandler(value = IndexOutOfBoundsException.class)
    public HashMap<String, Object> indexOutOfBoundsException(Exception e, Model model) {
		
		logger.error(e.getLocalizedMessage());
		
		HashMap<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("result", false);
		returnMap.put("message", "비정상적인 배열 정보를 확인 하고 있습니다.(IndexOutOfBoundsException)");
		
        return returnMap;
    }
	
	@ResponseStatus(value = HttpStatus.OK)
	@ExceptionHandler(value = ClassNotFoundException.class)
    public HashMap<String, Object> classNotFoundException(Exception e, Model model) {
		
		logger.error(e.getLocalizedMessage());
		
		HashMap<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("result", false);
		returnMap.put("message", "프로그램이 비정상 구동 되었습니다. 시스템 확인이 필요 합니다.(ClassNotFoundException)");
		
        return returnMap;
    }
	
	@ResponseStatus(value = HttpStatus.OK)
	@ExceptionHandler(value = PersistenceException.class)
    public HashMap<String, Object> persistenceException(Exception e, Model model) {
		
		logger.error(e.getLocalizedMessage());
		
		HashMap<String, Object> returnMap = new HashMap<String, Object>();
		returnMap.put("result", false);
		returnMap.put("message", "데이터 작업 중 문제가 발생 되었습니다.");
		
        return returnMap;
    }
	
}

service 및 repository 에서는 모든 예외를 throws 하고 ControllerAdvice를 이용해서 조건에 맞는 에러에 대한

응답을 json으로 사용자 화면에 출력 합니다.

이때 @ResponseStatus(value = HttpStatus.OK) 코드로 정상 응답이 된걸로 변경 해줍니다.

 

https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-controller-advice

 

Web on Servlet Stack

This part of the reference documentation covers support for Servlet stack, WebSocket messaging that includes raw WebSocket interactions, WebSocket emulation through SockJS, and publish-subscribe messaging through STOMP as a sub-protocol over WebSocket. 4.1

docs.spring.io

 

반응형
Posted by 질주하는구
,