IT/Spring

(Spring) 예외처리 [2015.04.07]

바바옄 2015. 4. 7. 17:29
반응형

p140 ~ p142 예외처리

exception handler 꼭 사용

@ControllerAdvice를 이용한 공통 익셉션 처리

src/main/java -> com.ktds.mcjang -> exception -> CommonExceptionHandler.java

package com.ktds.mcjang.exception;
 
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
 
// com.ktds 아래에서 발생하는 모든 Exception을 받겠다.
@ControllerAdvice("com.ktds")
public class CommonExceptionHandler {
    
    // 받아온 Exception이 RuntimeException일때 아래 메소드를 실행하겠다.
    // 동작하는 구조는 MVC와 동일하다.
    @ExceptionHandler(RuntimeException.class)
    public String getRuntimeExceptionHandler(){
        
        // WEB-INF/view/error/runtimeException
        return "error/runtimeException";
    }
    
    /* MVC 패턴
     @ExceptionHandler(RuntimeException.class)
    public ModelAndView getRuntimeExceptionHandler(RuntimeException exception){
        
        ModelAndView view = new ModelAndView();
        view.setViewName("error/runtimeException");
        view.addObject("message", exception.getMessage());
        return view;
        
        // WEB-INF/view/error/runtimeException
        //return "error/runtimeException";
    }
     
     */
 
}
 
cs

 

src -> main -> webapp -> WEB-INF -> VIEW -> error -> runtimeException.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
작업 처리 도중에 문제가 발생했습니다.
<%= exception %>
<!-- mvc 패턴: ${message}-->
</body>
</html>
 
cs

 

src/main/java -> com.ktds.mcjang -> board->  web -> BoardController.java

public void setBoardService(BoardService boardService) {
    this.boardService = boardService;
}
    
@RequestMapping(value="/write", method=RequestMethod.GET)
public ModelAndView viewWritePage(){
    ModelAndView view = new ModelAndView();
    view.setViewName("board/write");
        
    //오류 던지기
    throw new RuntimeException("페이지를 보여주기 싫어");
        
    //return view;
}
 
 
cs

 

반응형