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";
	}

 

+ Recent posts