이번에는 @ControllerAdvice입니다. 개인적으로 가장 효율적인 방법이라고 봅니다.
@ControllerAdvice
ControllerAdvice가 모든 컨트롤러에서 발생한 예외를 맡습니다.
예제
<web.xml>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/egovframework/springmvc/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<dispatcher-servlet.xml>
<bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver"></bean>
<ControllerAdvice 클래스>
@ControllerAdvice
public class ExampleAdvice extends ResponseEntityExceptionHandler {
/**
* 로그.
*/
private static final Log LOG = LogFactory.getLog(ExampleAdvice.class);
@ExceptionHandler(Throwable.class)
public String handleException(final Exception e, Model model) {
LOG.error("Throwable 예외 기록.", e);
model.addAttribute("msg", "오류 발생 시 메시지 추가 테스트입니다.");
return "/cmmn/egovError";
}
@ExceptionHandler(ExampleForbiddenException.class)
public String handleException(final ExampleForbiddenException e, Model model) {
LOG.error("ExampleForbiddenException 예외 기록.", e);
model.addAttribute("msg", "오류 발생 시 메시지 추가 테스트입니다.");
return "/cmmn/egovError";
}
}
장단점 설명
Controller에 Advice를 줄 용도로 만든 클래스에 [@ControllerAdvice]어노태이션을 붙인다. 클래스 내의 오류 처리 메서드에는 [@ExceptionHandler]어노태이션을 붙인다.
[@ExceptionHandler]어노태이션이 붙은 메서드가 동작하게 하려면 [ExceptionHandlerExceptionResolver]를 반드시 설정해야 한다.(Spring 3.1 이후에 DispatcherServlet에 기본으로 설정되어 있다고 하는데, 동작하지 않을 때는 명시적으로 설정하자.)
만약 특정 컨트롤러에서만 독자적인 오류 처리가 필요한 경우, 해당 컨트롤러 내에 예외 처리 메서드를 작성하고 [@ExceptionHandler]어노태이션을 붙이면 된다. ControllerAdvice의 [@ExceptionHandler]보다 컨트롤러 내의 [@ExceptionHandler]가 우선된다.
장점 : 전체 컨트롤러에서 발생하는 오류를 처리해주는 기능을 클래스 하나로 해결할 수 있다. 오류 로그를 남겨도 좋고, 다른 추가 처리를 해도 좋다. 특정 컨트롤러에서만 독자적인 오류 처리가 필요한 경우 분리시킬 수 있는 것도 장점.
단점 : 별달리 없다.
총평 : 가성비가 좋다. -_-)b
참고
- [Error Handling for REST with Spring]-[3.1. ExceptionHandlerExceptionResolver] : 예제 코드. 다만, [ExceptionHandlerExceptionResolver]가 필요하다는 설명이 있긴 하지만, 예제코드와 너무 떨어져 있어서 놓치기 쉽다.
- [[Spring] @ExceptionHandler가 동작하지 않을 때] : [ExceptionHandlerExceptionResolver]가 필수적으로 필요함을 알 수 있다. 내용 안의 관련 링크들도 읽어볼 만하다.
'컴 이것저것 > Java' 카테고리의 다른 글
파일 전송 시 boundary -httpClient (0) | 2024.09.03 |
---|---|
<Spring> Scheduler (0) | 2022.11.28 |
javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target (1) | 2022.08.29 |
Spring -ErrorPage[2] -ExceptionResolver (0) | 2022.08.03 |
Spring -ErrorPage[1] -어노태이션[@ResponseStatus] (0) | 2022.08.01 |