SPRING/스프링 MVC

예외 처리 핸들러: @ExceptionHandler

JUMP개발자 2021. 7. 13. 00:43

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

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

- 지원하는 리턴 값 

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

public class EventException extends RuntimeException{

}


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

    @ExceptionHandler({EventException.class, RuntimeException.class})
    public String eventErrorHandler(EventException exception, Model model) {
        model.addAttribute("message","event error");
        return "error";
    }

  // Exception화면
  @GetMapping("/events/exception")
  public String eventException(Model model) {
      throw new EventException();
  }

}

 

error.html 페이지

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Create New Event</title>
</head>
<body>
<div th:if="${message}">
    <h2 th:text="${message}"></h2>
</div>

</form>
</body>
</html>

 

- 컨트롤러에서 @ExceptionHandler를 사용한 메서드를 작성하여, 메서드 파라미터에 원하는 Exception을 넣으면 예외 처리를 핸들링할 수 있다.

- 위 예시의 경우 EventException 파라미터를 통하여 @ExceptionHandler를 호출한다.

- @ExceptionHandler에서는 error.html로 model 정보를 담아서 넘겨준다.

 

결과

 

@ExceptionHandler({EventException.class, RuntimeException.class})

-> 위와 같이 어노테이션에 Exception 클래스들을 선언하면 해당 Exception들만 핸들링한다.

 

@RestController에서 @ExceptionHandler 사용하기

@RestController
@RequestMapping("/api/events")
public class EventApi {

    @ExceptionHandler(EventException.class)
    public ResponseEntity eventErrorHandler(EventException exception, Model model) {
        return ResponseEntity.badRequest().body("EventExceptin ERROR 발생");
    }
    // 에러
    @PostMapping(value = "/error")
    public Event createEventWithException(HttpEntity<Event> request) {
        throw new EventException();
    }

}