• Home
  • About
    • Junseok photo

      Junseok

      개발자 블로그

    • Learn More
    • Facebook
    • Instagram
    • Github
  • Posts
    • All Posts
    • All Tags
  • Java
    • java-basic
    • java-solid
    • java-pattern
    • java-logging
  • Javascript
  • Angular
  • spring
    • spring-framework
    • spring-boot
    • spring-test
  • server
    • jeus
    • webtob
    • tomcat
  • test
    • junit
    • assertj
    • hamcrest
    • dbunit
    • spring
  • docker
  • unix
  • maven
  • db
  • network
  • eclipse
  • intellij
  • microservices
  • etc

Spring 예외 처리

17 Mar 2019

Reading time ~1 minute

ExceptionHandler

@Controller 및 @ControllerAdvice 클래스는 다음 예제와 같이 컨트롤러 메서드의 예외를 처리 할 수있는 @ExceptionHandler 메서드를 포함 할 수 있습니다.

@Controller
public class SimpleController {

    // ...

    @ExceptionHandler
    public ResponseEntity<String> handle(IOException ex) {
        // ...
    }
}

일치하는 예외 유형의 경우 메서드 파라미터로 선언하는 것이 바람직 합니다. 여러 예외 메소드가 일치하면 일반적으로 원인 예외 일치보다 루트 예외 일치가 선호됩니다.

일치하는 예외 유형을 좁힐 수 있습니다.

@ExceptionHandler({FileSystemException.class, RemoteException.class})
public ResponseEntity<String> handle(IOException ex) {
    // ...
}

메서드 파라미터를 가장 일반적인 Exception 클래스로 선언할 수도 있습니다.

@ExceptionHandler({FileSystemException.class, RemoteException.class})
public ResponseEntity<String> handle(Exception ex) {
    // ...
}

Spring MVC에서 @ExceptionHandler 메소드를 지원하는 것은
DispatcherServlet 레벨 인 HandlerExceptionResolver 메커니즘을 기반으로 합니다.

@ExceptionHandler 메서드는 다음의 arguments 지원합니다.

  • Exception type
  • HandlerMethod
  • WebRequest, NativeWebRequest
  • javax.servlet.ServletRequest, javax.servlet.ServletResponse
  • javax.servlet.http.HttpSession
  • java.security.Principal
  • HttpMethod
  • java.util.Locale
  • java.util.TimeZone, java.time.ZoneId
  • java.io.OutputStream, java.io.Writer
  • java.util.Map,org.springframework.ui.Model,org.springframework.ui.ModelMap
  • RedirectAttributes
  • @SessionAttribute
  • @RequestAttribute

@ExceptionHandler 메서드는 다음의 return type을 지원합니다.

  • @ResponseBody
  • HttpEntity, ResponseEntity
  • String
  • View
  • java.util.Map, org.springframework.ui.Model
  • @ModelAttribute
  • ModelAndView object
  • void
  • Any other return value

ControllerAdvice

일반적으로 @ExceptionHandler, @InitBinder 및 @ModelAttribute 메서드는 선언 된 @Controller 클래스 (또는 클래스 계층 구조) 내에 적용됩니다. 그러한 메소드가 (컨트롤러를 넘어서)보다 전역 적으로 적용되기를 원하면 @ControllerAdvice 또는 @RestControllerAdvice로 표시된 클래스에서 선언 할 수 있습니다.

@ControllerAdvice는 @Component로 표시되어 있습니다. 즉, 컴포넌트 검색을 통해 Spring Bean으로 등록 될 수 있습니다.
@RestControllerAdvice는 @ControllerAdvice 및 @ResponseBody가 모두 표시된 메타-어노테이션으로, 기본적으로 @ExceptionHandler 메소드가 메시지 변환 (뷰 해상도 또는 템플리트 렌더링)을 통해 응답 본문에 렌더링된다는 의미입니다.

ControllerAdvice의 요청을 좁힐 수 있습니다.

// @RestController 애너테이션이 달린 모든 대상
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}

// org.example.controllers 패키지안의 모든 @Controller
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}

// 특정 클래스에 할당 할 수있는 모든 컨트롤러 대상 지정
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvice3 {}


springframeworkexception Share Tweet +1