[Spring] 예외처리

개발log·2024년 3월 17일

Spring

목록 보기
5/16
post-thumbnail

예외 발생시키기

RuntimeException - 서버 에러

@RestController
@RequestMapping("/api")
public class RestApiController {
    @GetMapping(path="")
    public void hello(){
        throw new RuntimeException("run time exception call");

    }
}

console

  • 서버 에러 발생
java.lang.RuntimeException: run time exception call

IndexOutOfBoundsException - 범위를 벗어난 인덱스

  • list는 현재 단일 요소이므로 2번째 요소 반환 불가(에러발생)
@GetMapping(path="")
    public void hello(){
        var list = List.of("hello"); //[hello]
        var element = list.get(1);// 현재 리스트는 단일 요소이므로 에러 발생
        log.info("element : {}", element);
    }

console

java.lang.IndexOutOfBoundsException: Index: 1 Size: 1

예외처리

  • @RestControllerAdvice Rest API가 사용하는 곳(모든 컨트롤러)에 예외가 일어나는 것을 감지
  • @ExceptionHandler(value = {Exception.class}) 예외처리 하고자 하는 클래스를 넣음
  • @ExceptionHandler(value = {NumberFormatException.class})
    해당 예외는 해당 컨트롤러에서 처리(@RestControllerAdvice보다 우선)
    - @RestControllerAdvice(basePackages = "com.example.exception.controller")
    예외 처리를 담당하는 클래스가 위치한 패키지를 지정
  • @RestControllerAdvice(basePackageClasses = {RestApiController.class, RestApiController2.class}) 예외 처리 할 특정 클래스 지정

모든 예외 감지 및 처리

@Slf4j
@RestControllerAdvice //Rest API가 사용하는 곳에 예외가 일어나는 것을 감지
public class RestApiExceptionHandler {
    @ExceptionHandler(value = {Exception.class})//예외처리 하고자 하는 클래스를 넣음
    public ResponseEntity exception(Exception e){
        log.error("RestApiExceptionHandler",e);

        return ResponseEntity.status(200).build();
    }

    @ExceptionHandler(value = {IndexOutOfBoundsException.class})// 특정 예외 처리(예외 처리할 곳 지정)
    public ResponseEntity outOfBound(IndexOutOfBoundsException e){
        log.error("IndexOutOfBoundsException ",e);
        return ResponseEntity.status(200).build();
    }
}

console

  • 예외가 발생하였지만, 응답은 성공인 것을 알 수 있음.
  • status 지정 및 에러처리하였기 때문
2024-03-17T14:02:14.542+09:00 ERROR 1092 --- [exception] [nio-8080-exec-1] c.e.e.exception.RestApiExceptionHandler  : RestApiExceptionHandler

java.lang.IndexOutOfBoundsException: Index: 1 Size: 1
	at java.base/java.util.ImmutableCollections$AbstractImmutableList.

현 컨트롤러에서 예외 처리

@Slf4j
@RestController
@RequestMapping("/api/2")
public class RestApiController2 {
    @GetMapping("/hello")
    public void hello(){
        throw new NumberFormatException("NumberFormatException");
    }
    @ExceptionHandler(value = {NumberFormatException.class})
    // 해당 예외는 해당 컨트롤러에서 처리(@RestControllerAdvice보다 우선)
    public ResponseEntity numberFormatException(NumberFormatException e){
        log.info("RestApiController2", e);

        return ResponseEntity.ok().build();
    }
}

예외 처리 클래스가 위치한 패키지를 지정

  • 해당 패키지에 속한 컨트롤러에서 발생하는 예외를 처리할 수 있는 예외 처리 클래스를 정의
@Slf4j
@RestControllerAdvice(basePackages = "com.example.exception.controller")
public class RestApiExceptionHandler {
    @ExceptionHandler(value = {Exception.class})//예외를 잡고자 하는 클래스를 넣음
    public ResponseEntity exception(Exception e){
        log.error("RestApiExceptionHandler",e);

        return ResponseEntity.status(200).build();
    }

    @ExceptionHandler(value = {IndexOutOfBoundsException.class})// 특정 예외 처리(예외 처리할 곳 지정)
    public ResponseEntity outOfBound(IndexOutOfBoundsException e){
        log.error("IndexOutOfBoundsException ",e);
        return ResponseEntity.status(200).build();
    }
}

예외처리 할 특정 클래스 지정

  • 해당 클래스가 속한 패키지에 있는 컨트롤러에서 발생하는 예외 처리
@Slf4j
//특정 클래스 지정
@RestControllerAdvice(basePackageClasses = {RestApiController.class, RestApiController2.class})
public class RestApiExceptionHandler {
    @ExceptionHandler(value = {Exception.class})//예외를 잡고자 하는 클래스를 넣음
    public ResponseEntity exception(Exception e){
        log.error("RestApiExceptionHandler",e);

        return ResponseEntity.status(200).build();
    }
profile
나의 개발 저장소

0개의 댓글