티스토리 뷰

BackEnd/Spring

[Spring] 예외처리

best 2016. 4. 14. 16:42

1. web.xml 에서의 에러페이지 처리


<error-page>를 사용한다.


<error-code>  는 Http 상태코드를 의미한다.

<exception-type> 는 서버가 던진 exception을 의미한다.


error-code 와 exception-type 둘 중 하나만 선택해서 쓴다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
  <error-page>
      <error-code>400</error-code>
      <location>/WEB-INF/view/error/400.jsp</location>
  </error-page>
  
  <error-page>
      <error-code>404</error-code>
      <location>/WEB-INF/view/error/404.jsp</location>
  </error-page>
  
   <error-page>
      <error-code>500</error-code>
      <location>/WEB-INF/view/error/500.jsp</location>
  </error-page>
cs



2. @ControllerAdvice 를 이용한 공통 Exception 처리

지정된 패키지 하위에서 Exception이 발생한 경우 Exception을 공통된 로직으로 처리해준다.


EX ) @ControllerAdvice("com.ktds") : com.ktds 아래에서 발생하는 모든 에러들을 처리한다는 의미



 - Exception Handler 생성



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.ktds.jmj.handler;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
 
// com.ktds.jmj 아래에서 발생되는 모든 에러들을 확인한다.
// 에러가 발생하면 ExceptionHandler에 먼저 들어왔다가 간다.
@ControllerAdvice("com.ktds.jmj")
public class CustomExceptionHandler {
    
    // class<?extends throwable> []   throwable을 상속받고 있는 모든 클래스 중 어떤 것이 올지 모른다.
    @ExceptionHandler({RuntimeException.class})
    public ModelAndView runtimeExceptionHandler(RuntimeException re, HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        
        view.setViewName("error/500");
        view.addObject("message", re.getMessage());
        String referer = request.getHeader("Referer"); // 링크를 클릭한 위치
        view.addObject("from", referer);
        view.addObject("content""내가 보냄?");
        return view;
    }
}
 
cs



- dispatcherServlet에 등록


Controller와 마찬가지로 dispatcherServlet에 등록해준다.


<bean id="customExceptionHandler" class="com.ktds.jmj.handler.CustomExceptionHandler" />




- Error Page 작성


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${ content } <br/>
${ message } <br/>
${ from } <br/>
요청 작업 처리 중 에러가 발생했습니다.
잠시 후 다시 시도해주세요.
</body>
</html>
cs





- 결과 화면





'BackEnd > Spring' 카테고리의 다른 글

[Spring] 파일 업로드  (0) 2016.04.20
[Spring] Controller의 리턴 타입  (0) 2016.04.15
[Spring] Command 객체 값 검증, Error 메세지  (0) 2016.04.14
[Spring] Redirect 처리  (0) 2016.04.14
[Spring] Spring 기본 4 (MVC)  (0) 2016.04.12
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함