ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Application 예외 처리
    Java/Spring 2018. 8. 24. 15:53
    반응형

    웹 페이지를 이용하다보면 Page Error 404, 505등 페이지 에러가 나타난다.


    해당 에러 페이지에는 민감한 정보가 그대로 노출되기때문에 예외처리를 통해 페이지를 구성해야 한다.


    view 폴더 아래 errors 폴더를 만들고 jsp파일을 만든다.



    <!-- 404.jsp -->
    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>404 Not Found</title>
    </head>
    <body>
        <p>페이지를 찾을 수 없습니다.</p>
        <h4>
            <a href="/HelloSpring/board/list">홈으로 돌아가기</a>
        </h4>
    </body>
    </html>


    500.jsp


    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>500 Not Found</title>
    </head>
    <body>
        <p>
            일시적 오류로 인해 페이지를 표시할 수 없습니다.<br />
            잠시 후 다시 시도해 주세요.<br />
            이 페이지가 계속 보인다면, 사이트 관리자에게 문의해 주세요.
        </p>
        <h4>
            <a href="">고객센터 바로가기</a>
        </h4>
        <h4>
            <a href="/HelloSpring/board/list">홈으로 돌아가기</a>
        </h4>
    </body>
    </html>


    상황별 예외 처리를 위해 web.xml에서 throwExceptionIfNoHandlerFound param을 추가한다.


    <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
    <servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param> <!-- Setter -->
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring/applicationContext.xml</param-value>
    </init-param>
    <init-param>
    <param-name>throwExceptionIfNoHandlerFound</param-name>
    <param-value>true</param-value> <!-- Argument -->
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>


    상위 package에 ExceptionController Class를 작성한다.


    package com.ktds.common.exceptions.handler;

    import java.io.UnsupportedEncodingException;
    import java.net.URLEncoder;

    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.servlet.NoHandlerFoundException;

    import com.ktds.common.exceptions.PolicyViolationException;

    @ControllerAdvice // Controller와 동일한 역할 수행, 예외 발생시 예외만 처리
    public class GlobalExceptionHandler {
        
        // NoHandlerFoundException 예외가 발생했을때 해당 메소드 처리
        @ExceptionHandler(NoHandlerFoundException.class)
        public String noHandlerFoundExceptionHandler() {
            return "errors/404";
        }
        
        @ExceptionHandler(RuntimeException.class)
        public String RuntimeExceptionHandler( RuntimeException e )
                 throws UnsupportedEncodingException {
            // e.printStackTrace(); // 어느 Error인지 볼 때만 잠시 사용.
            
            if ( e instanceof PolicyViolationException ) { // Type 확인
                PolicyViolationException pve = (PolicyViolationException) e; // Casting
                return "redirect:"
                + pve.getRedirect()
                + "?message="
                + URLEncoder.encode(pve.getMessage(), "UTF-8"); // UTF-8 처리, Add throw
            }
            
            return "errors/500";
        }
        
    }


    Runtime Exception을 상속받는  PolicyViolationException 도 만들어서 Type을 비교 후

    if문안에 구문을 처리한다.


    package com.ktds.common.exceptions;

    public class PolicyViolationException extends RuntimeException {
        
        private String message;
        private String redirectUri;
        
        public PolicyViolationException(String message, String redirectUri) {
            this.message = message;
            this.redirectUri = redirectUri;
        }

        public String getMessage() {
            return message;
        }
        
        public String getRedirect() {
            return redirectUri;
        }
        
    }




    @ControllerAdvice // Controller와 동일한 역할 수행, 예외 발생시 예외만 처리

    @ControllerAdvice("") -> ("package") 해당 package이하에서 catch되지 않는 Exception발생시 해당 클래스가 동작한다.

    Spring이 관리할 대상이기 때문에 applicationContext.xml에 등록이 필요하다.


    @ExceptionHandler(RuntimeException.class) @RequestMapping과 동일한 역할을 수행하고

    발생한 Exception이 RuntimeException일 경우 해당 메소드가 동작한다.


    Controller에서 Exception이 발생한 것을 DispatcherServlet -> JVM으로 가기전에 DispatcherServlet으로 가기전에

    @ControllerAdvice를 통해 예외를 먼저 잡는다.

    어떤 에러를 어떻게 잡을것인지는 @ExceptionHandler(Exception.class)를 통해 구현할 수 있다.



    반응형

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

    Interceptor  (0) 2018.08.24
    bean config 설정 분리  (0) 2018.08.24
    File - Upload / Download  (0) 2018.08.23
    Session  (0) 2018.08.23
    Spring - JSTL  (0) 2018.08.22

    댓글

Designed by Tistory.