그라가승훈
[SpringBoot] - @ControllerAdvice 를 이용한 전역 예외처리 본문
- 예외처리
스프링의 예외처리 방법에는 크게 세 가지가 있다.
- try/catch 를 이용한 예외처리
- 각각의 컨트롤러단에서 @ExceptionHandler 를 이용한 예외처리
- @ControllerAdvice 를 이용한 전역 예외처리
여기서는 @ControllerAdvice 를 이용한 전역 예외처리를 볼 것이다.
1. @ControllerAdvice 추가하기
스프링 3.2에서 추가된 어노테이션으로 스프링부트 2.0 이상부터는 @ControllerAdvice 어노테이션만 사용하면 추가적인 설정 없이 쉽게 예외처리할 수 있다.
- common 패키지를 생성 후 ExceptionHandler 클래스를 생성
@ControllerAdvice
@Slf4j
public class ExceptionHandler {
// 실제로는 각 exception 마다 처리를 해야하지만 지금은 기능만 확인
@org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
public ModelAndView defaultExceptionHandler(HttpServletRequest request, Exception exception) {
ModelAndView mv = new ModelAndView("/error/error_default");
mv.addObject("exception", exception);
log.error("exception", exception);
return mv;
}
}
실제 프로젝트에서는 절대로 Exception 클래스를 이용해서 한번에 모든 예외를 처리하지 않도록 주의!
- 에러처리 화면 추가
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>공통 에러 페이지</title>
<link rel="stylesheet" th:href="@{/css/style.css}"/>
</head>
<body>
<p>공통 에러 페이지</p>
<p th:text="${exception}"></p>
<ul th:each="list: ${exception.getStackTrace()}"
th:text="${list.toString()}"></ul>
</body>
</html>
실제 프로젝트에서는 에러로그를 화면에 직접 보여주면 프로그램의 취약점이 드러나 공격받을 수 있음.
2. 에러로그 및 공통 에러 페이지 결과 확인.
- 에러로그
- 공통 에러 페이지
'Spring' 카테고리의 다른 글
[SpringBoot] - 파일 업로드와 다운로드 (1) | 2023.10.16 |
---|---|
[SpringBoot] - Mybatis 설정 (0) | 2023.10.15 |
[SpringBoot] - AOP (2) | 2023.10.15 |
[SpringBoot] - 인터셉터(Interceptor) (0) | 2023.10.15 |
[SpringBoot] -Logback 사용하기 - (Slf4j, log4jdbc, p6spy) (0) | 2023.10.13 |
Comments