@ControllerAdvice로 전역 예외 처리 클래스 작성 가능(패키지 지정 가능)
예외 처리 메서드가 중복된 경우, 컨트롤러 내의 예외 처리 메서드가 우선
@Controller
public class ExceptionController {
@ExceptionHandler({NullPointerException.class, FileNotFoundException.class})
public String catcher2(Exception ex, Model m){
m.addAttribute("ex", ex);
return "error";
}
@RequestMapping("/ex2")
public String main2() throws Exception {
throw new NullPointerException("예외가 발생했습니다.");
}
}
Global Catcher로 처리
@ControllerAdvice
public class GlobalCatcher {
@ExceptionHandler({NullPointerException.class, ClassCastException.class})
public String catcher2(Exception ex) {
return "error";
}
}
@ResponseStatus
1. 응답 메세지의 상태 코드를 변경할 때 사용
예외처리를 하면 200번 성공이 나오므로 400 또는 500번으로 변경 해야함.
디폴트는 500번 Internal Server Error
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) //405
@ExceptionHandler({NullPointerException.class, ClassCastException.class})
public String catcher2(Exception ex, Model m) {
m.addAttribute("ex", ex);
return "error";
}
@ResponseStatus(HttpStatus.BAD_REQUEEST) //400
class MyException extends RuntimeException {
MyException(String msg) {
super(msg);
}
MyException() {
this("");
}
}
jsp에 isErrorPage="true"를 추가해주면
EL로
발생한 예외 : ${pageContext.exception}
예외 메세지 : ${pageContext.exception.message}
<c:forEach item="${pageContext.exception.stackTrace}" var="i">
<li>${i.toString()}</li>
</c:forEach>
이렇게 사용 가능.
web.xml에 "예외코드별"로 추가가능
<error-page>
<error-code>400</error-code> //상태코드
<location>/error400.jsp</location> //뷰 위치, 이름
</erorr-page>
<erorr-page>
<error-code>500</error-code>
<location>/error500.jsp</location>
</error-page>
SimpleMappingExceptionResolver
servlet-context.xml에 "예외 종류별"로 뷰 맵핑 등록 가능
<beans:props>
<beans:prop key="com.fastcampus.ch2.MyException">error400</beans:prop>
</beans:props>
<beans:property name="statusCodes">
<beans:props>
<beans:prop key="error400">404</beans:prop>
</beans:props>
</beans:property>
스프링에서의 예외처리