웹프로그래밍/spring

스프링4.0- 익셉션 처리

Gamcho 2018. 7. 18. 13:23

@ExceptionHandler

해당 컨트롤러에서 발생한 익셉션만 처리

@ExceptionHandler의 값으로 넣은 익셉션이 발생하면 메서드에서 익셉션 처리 후 리턴한 뷰로 이동 

응답코드는 기본 200이다. 다른 응답 코드를 전송하려면 HttpServletResponse 파라미터를 추가하고 setStatus() 메서드로 응답코드를 지정한다.

HttpSession, Model도 파라미터로 쓸 수 있다.

응답코드에 따라서 익셉션 페이지가 다르다.


-컨트롤러 클래스

//RuntimeException은 슈퍼 클래스로 하위의 uncheckedexception을 모두 포함한다.

//즉 모든 익셉션을 잡아낸다.

@ExceptionHandler(RuntimeException.class)

public String handleException(HttpServletResponse response) {

////500 응답 코드 전송

response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

return "error/exception";

}


-뷰

<%@ page contentType="text/html; charset=utf-8" %>

<%@ page isErrorPage="true" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html>

<head>

<title>에러 발생</title>

</head>

<body>


작업 처리 도중 문제가 발생했습니다.

<%= exception %>


</body>

</html>



@ControllerAdvice

다수의 컨트롤러에서 동일한 타입의 익셉션 처리할때 사용

우선 순위는 컨트롤러 클래스 안에 있는 @ExceptionHandler의 익셉션 타입이 더 높다.


-빈 등록

<bean class="net.madvirus.spring4.chap07.exhandler.CommonExceptionHandler"/>


-익셉션을 처리할 클래스 생성

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ExceptionHandler;


//익셉션 처리 범위 지정

@ControllerAdvice("net.madvirus.spring4.chap07")

public class CommonExceptionHandler {


@ExceptionHandler(RuntimeException.class)

public String handleException() {

return "error/commonException";

}

}


@ResponseStatus

익셉션 자체에 에러 응답 코드를 설정할때 사용


-익셉션을 처리할 클래스 생성

import org.springframework.http.HttpStatus;

import org.springframework.web.bind.annotation.ResponseStatus;


@ResponseStatus(HttpStatus.NOT_FOUND)

public class NoFileInfoException extends Exception {


private static final long serialVersionUID = 1L;


}


-컨트롤러

@RequestMapping(value = "/files/{fileId:[a-zA-Z]\\d{3}}", method = RequestMethod.GET)

public String fileInfo(@PathVariable String fileId) throws NoFileInfoException {

FileInfo fileInfo = getFileInfo(fileId);

if (fileInfo == null) {

throw new NoFileInfoException();

}

return "files/fileInfo";

}