Today
-
Yesterday
-
Total
-
  • Spring Boot: Exception 처리
    Spring Boot 🍃 2023. 12. 4. 00:01

    보고 배운 인강 1 링크 보고 배운 인강 2 링크

    예외란? Exception ?

    프로그램이 예상치 못한 상황을 만났을 때 오류를 발생시키는 것


    스프링 MVC에서 예외를 처리하는 방법

    REST API : RestControllerAdvice ViewResolver : ControllerAdvice

    @RestControllerAdvice

    어플리케이션의 전역적 예외 처리

    REST API용으로 객체를 응답하는 방식 (주로 JSON)


    옵션 값 지정으로 특정 패키지 혹은 특정 클래스에서 발생하는 예외만 처리하는 파일을 만들수도 있다.

    1. 특정 패키지에서 발생하는 예외만 처리
    @RestControllerAdvice(basePackages = "com.example.dice.controller") 
    
    2. 특정 클래스에서 발생하는 예외만 처리
    @RestControllerAdvice(basePackageClasses = ExceptionController.class) 

    @ExceptionHandler

    • 예외처리 우선순위

      1. 해당 Exception이 정확히 지정된 Handler
      2. 해당 Exception의 부모 예외 Handler
      3. Exception
    • 사용 방법1. RestControllerAdvice에서 전역 예외처리기로 사용

      @RestControllerAdvice
      public class GlobalControllerAdvice {
            @ExceptionHandler(value = Exception.class)
            public ResponseEntity<?> exceptionProcess(Exception e) {
      
              log.error("============ advice ============");
              log.error("message : {}", e.getLocalizedMessage());
      
              return ResponseEntity.status(INTERNAL_SERVER_ERROR).body("");
           }
      }
    • 사용 방법 2. 특정 Controller에서 전용 예외 처리기로 사용

      @RestController
      public class UserController {
      		@GetMapping
            public ResponseEntity<?> get(){ ... }
            
      		@PostMapping
            public ResponseEntity<?> save(){ ... }
            
            
            @ExceptionHandler(value = Exception.class)
            public ResponseEntity<?> exceptionProcess(Exception e) {
      
              log.error("============ user controller ============");
              log.error("message : {}", e.getLocalizedMessage());
      
              return ResponseEntity.status(INTERNAL_SERVER_ERROR).body("");
           }
      }



    만약,

    Advice로 예외 처리를 해놓은 프로젝트에서, Controller에 ExceptionHandler를 작성한 경우

    예외 처리를 Controller의 ExceptionHandler에서 하게 된다.

    만약, Controller에서 잡히지 못한 예외인 경우 Advice에서 처리 됨



    @ControllerAdvice

    view를 응답하는 방식

    'Spring Boot 🍃' 카테고리의 다른 글

    spring boot: Slf4j  (0) 2023.12.05
    Spring Boot: Filter  (0) 2023.12.04
    정규식 모음  (0) 2023.12.04
    Spring Boot: 유효성 검증 Validation  (0) 2023.12.04
    Spring boot: Pageable  (0) 2023.12.04

Designed by Tistory / Custom by 얼거스