본문으로 바로가기

[Spring MVC] @ExceptionHandler

category Spring/SpringMVC 2019. 8. 24. 09:42

@ExceptionHandler

: 특정 예외가 발생한 요청을 처리하는 핸들러를 정의한다.

  - 지원하는 메소드 아규먼트( 해당 예외 객체, 핸들러 객체 , ...)

  - 지원하는 리턴 값

  - REST API의 경우 응답 본문에 에러에 대한 정보를 담아주고 , 상태 코드를 설정하려면 ResponseEntity를

    주로 사용한다.

 

 

package com.example.demo;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@SessionAttributes("event")
public class EventController {

	@ExceptionHandler({EventException.class , RuntimeException.class})
	public String ErrorHandler(RuntimeException exception , Model model) {
		model.addAttribute("message","Exception error");
		//가장 구체적인 에러를 잡음
		return "/files/error";
	}
	
	@ExceptionHandler
	public String eventErrorHandler(RuntimeException exception , Model model) {
		model.addAttribute("message","event error");
		//가장 구체적인 에러를 잡음
		return "/files/error";
	}

	@InitBinder("event")
	public void initEventBinder(WebDataBinder webDataBinder) {
		webDataBinder.setDisallowedFields("id"); //받고 싶지 않은 필드를  설정할수있다.
		webDataBinder.addValidators(new EventValidator());
	}
	
	
	@ModelAttribute
	public void categories(Model model) {
		model.addAttribute("subjects",List.of("study","seminar","hobby"));
	}
	
	
	
	@GetMapping("/events/form/name")
	public String eventFormName(Model model) {
		
		throw new EventException();
		
		/*
		 * model.addAttribute("event", new Event()); return "/events/form-name";
		 */
	}


}
package com.example.demo;

public class EventException extends RuntimeException{

}
<error.html>

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="EUC-KR">
<title>File Upload</title>
</head>
<body>


<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>

   
</body>
</html>

 

위의 코드를 보면 메소드 eventFormName에서 예외를 발생시킨다.

예외가 발생되면 가장 ExceptionHandler 중에서 가장 구체적인 예외를 잡는다.

또한 ExceptionHandler에서 여러 에러를 하나의 메소드에서 잡을수있다.