-web.xml 에서 serlvet태그에 throwExceptionIfNoHandlerFound을 요소로 추가해주면서
404 에러도 DispatcherServlet을 이용해서 같이 처리될 수 있도록 만들어준다.
알게된 내용
-생성자를 롬복으로 만들어주면안된다. 이유는 매개변수를 메세지를 받는 생성자를 만들기 위해서
public class ControllerException extends Exception{
private static final long serialVersionUID =1L;// 컴파일된 클래스의 버젼
public ControllerException(String message) {
super(message);
}// Constructor
public ControllerException(Exception e) {
super(e);
}// Constructor
}//end class
.getStackTrace 가 반환하는 값은 에러 스택에 대한 흐름
StackTraceElement[] getStackTrace() - 예외가 발생했을 당시의 스택정보를 StackTraceElement 배열로 반환. StackTraceElement는 스택에 대한 요소들임
.getCause() 예외처리시 원인 객체를 보여준다.
Throwable getCause() - 예외가 발생한 근본적인 원인 예외를 반환. 원인 객체가 없는 경우 null을 반환함
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>errorPage</title>
</head>
<body>
<h1>/WEB-INF/views/errorPage.jsp</h1>
<hr>
<p>${ _EXCEPTION_ }</p>
<ol>
<c:forEach var="element" items="${ _EXCEPTION_.getStackTrace() }">
<li>at ${element}</li>
</c:forEach>
</ol>
<hr>
<p>Caused by ${ _EXCEPTION_.getCause() }</p>
<ol>
<c:forEach var="oelement" items="${ _EXCEPTION_.getCause().getStackTrace() }">
<li>at ${oelement}</li>
</c:forEach>
</ol>
</body>
</html>
1. @@ControlleraAdvice에 대해
2. @ExceptionHandler에 대해
3. model 상자에 예외 객체를 넣는다.
4. exception처리하는 것은 위에서 부터 메소드 선언된 순서와 관련없음
5. @ResponseStatus 어노테이션과 HttpStatus.~~ 에 대하여
package org.zerock.myapp.exception;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;
@NoArgsConstructor
@Log4j2
@ControllerAdvice
public class CommonsExceptionHandler {
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // HTTP status code = 500
@ExceptionHandler( Exception.class )
public String handleException(Exception e, Model model) { // 모든 예외의 처리 핸들러
log.trace("handleException({}, {}) invoked.", e, model);
model.addAttribute("_EXCEPTION_", e);
return "errorPage"; // 뷰의 이름 반환
} // handleException
@ResponseStatus(HttpStatus.BAD_REQUEST) // HTTP status code = 400
@ExceptionHandler( ControllerException.class )
public String handleControllerException(Exception e, Model model) {
log.trace("handleControllerException({}, {}) invoked.", e, model);
model.addAttribute("_EXCEPTION_", e);
return "errorPage"; // 뷰의 이름 반환
} // handleControllerException
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) // HTTP status code = 405
@ExceptionHandler( NoHandlerFoundException.class )
public String handleNoHandlerFoundException(Exception e, Model model) {
log.trace("handleNoHandlerFoundException({}, {}) invoked.", e, model);
model.addAttribute("_EXCEPTION_", e);
return "errorPage"; // 뷰의 이름 반환
} // handleNoHandlerFoundException
}//end class