ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [spring boot] 에러 핸들링 @ExceptionHandler @ControllerAdvice
    spring boot 2024. 1. 25. 00:05

    Spring의 예외 처리방법


     

    1. Controller내에서의 Error handling

    package com.example.demo.controller;
    
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @RestController
    public class Controller {
    
        @PostMapping("/exception")
        public void exceptionTest() throws Exception {
            throw new Exception();
        }
    
        @ExceptionHandler(value = Exception.class)
        public ResponseEntity<Map<String, String>> exceptionHandler() {
            HttpHeaders httpHeaders = new HttpHeaders();
    
            HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
    
            Map<String, String> map = new HashMap<>();
            map.put("error type", httpStatus.getReasonPhrase());
            map.put("status code", "400");
            map.put("message", "error");
    
            return new ResponseEntity<>(map, httpHeaders, httpStatus);
    
        }
    
    }

     

    2. @ControllerAdvice를 사용한 예외 처리

    package com.example.demo.exception;
    
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RestControllerAdvice;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @RestControllerAdvice  // 예외 발생 시 json의 형태로 결과를 반환하기 위해서는 @RestControllerAdvice 사용
    public class MyExceptionHandler {
    
        @ExceptionHandler(value = Exception.class)
        public ResponseEntity<Map<String, String>> exceptionHandler() {
            HttpHeaders httpHeaders = new HttpHeaders();
    
            HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
    
            Map<String, String> map = new HashMap<>();
            map.put("error type", httpStatus.getReasonPhrase());
            map.put("status code", "400");
            map.put("message", "error");
    
            return new ResponseEntity<>(map, httpHeaders, httpStatus);
    
        }
    
    }

    두 방법을 보면 차이점이 뭐지 싶을 것이다.

    두 방법의 차이점은 같은 에러 발생시 어떤 예외 처리를 우선 순으로 두는가 이다.

    Controller와 ControllerAdvice 내에 둘다 동일한 ExceptionHandler가 존재한다면 Controller 내에 있는 ExceptionHandler가 우선순위를 갖는다.

    댓글

Designed by Tistory.