1. 에러를 처리할 패키지 생성
2. 에러 처리할 파일 작성
package <-- 1에서 만든 패키지-->;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import lombok.extern.log4j.Log4j;
@ControllerAdvice
@Log4j
public class CommonExceptionAdvice {
@ExceptionHandler(Exception.class)
public String exception(Exception exception, Model model) {
log.error(exception.getMessage()); //콘솔에서 로그 확인
return "error_page"; //해당 에러페이지 출력
}
}
3. servlet-context.xml에서 스캔하도록 추가
<context:component-scan base-package="<-- 해당 에러 패키지-->"/>
** 404의 경우
1. web.xml 수정(throwExceptionIfNoHandlerFound 추가)
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<init-param>
<param-name>throwExceptionIfNoHandlerFound</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
2. 에러 처리 파일에 메소드 추가
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handle404(NoHandlerFoundException exception) {
return "error_page";
}
'spring' 카테고리의 다른 글
tomcat war 배포 시 404 오류(feat. 로컬에선 잘돌아갔는데..?) (0) | 2021.05.07 |
---|---|
[스프링] 프로젝트 초기 설정 하기 (0) | 2021.04.29 |