본문 바로가기
SpringBoot/(책)스프링부트 시작하기

[springboot] 9. 예외처리하기

by 평범한kiki 2023. 4. 25.

* 예외처리하기
- try/catch 사용한 예외처리
- 각각 컨트롤러단에서 @ExceptionHandler를 이용한 예외처리
- @ControllerAdvice를 이용한 전역 예외처리

@ControllerAdvice는 스프링 3.2에서 추가된 어노테이션으로 xml에 설정이 필요했지만,
스프링 부트에서는 @ControllerAdvice를 통해서 추가적인 설정없이 쉽게 예외처리가능

 

* @ControllerAdvice 설정하기

/board/src/main/java/board/common/ExceptionHandlerControllerAdvice.java

package board.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import jakarta.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ExceptionHandlerControllerAdvice {

	private Logger log = LoggerFactory.getLogger(this.getClass());

	@ExceptionHandler(ArithmeticException.class)
	public String arithmeticExceptionHandler(HttpServletRequest request, ArithmeticException exception, Model model) {
		model.addAttribute("exception", exception);
		log.error("ArithmeticException", exception);
		
		return "error/error_default";
	}

	
	@ExceptionHandler(Exception.class)
	public String defaultExceptionHandler(HttpServletRequest request, Exception exception, Model model) {
		model.addAttribute("exception", exception);
		log.error("exception", exception);
		
		return "error/error_default";
	}

}
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer{

	//인터셉터 등록 addPathPatterns():요청주소의 패턴/excludePathPatterns():제외 주소의 패턴
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new LoggerInterceptor())
		        .order(1)
		        .addPathPatterns("/**")
		        .excludePathPatterns("/css/**","/error", "/error/**"); // 위처럼 인터셉터는 등록시 중복 호출이 일어나지 않도록 URL 패턴을 지정해주면 된다.
	}

}