에외처리

예외 처리의 방법

  • 예외 복구
    • 예외가 발생하면 예외 상황에 대해 알맞게 처리하여 복구한다.(try catch)
  • 예외 회피
    • 예외를 직접 처리하지 않고 예외를 상위 메서드에 위임한다.(throw)
  • 예외 전환
    • 예외를 위임하되 발생한 예외를 그대로 위임하는 것이 아닌 적절한 예외로 전환하여 위임한다.(restTemplate.doExcute)

예외 복구 범위

  • 메서드 영역
    • 메서드 영역은 종속된 복구 기능으로 단순히 try catch 사용하면 된다.
  • 클래스 영역
    • 클래스 내 공통 예외 복구는 @ExceptionHandler 사용할 수 있다.
  • 전역 영역
    • @ControllerAdvice 사용할 수 있다.

컨트롤러 내 예외처리

  • 특정 컨트롤러 내부에서 예외를 처리하고 싶을 경우 @ExceptionHandler를 사용하여 해결하자 이는 @Controller 나 @RestController 빈 내에서 발생하는 특정 예외를 처리해주는 기능을 지원한다.
@ExceptionHandler({NullPointerException.class, ClassCastException.class})
    public String handle(Exception ex){
        return "Exception Handle!!!";
    }

글로벌 예외처리

  • 특정 컨트롤러가 아닌 여러 컨트롤러로 공통된 로직을 구현하기 위해서 @ControllerAdvice를 사용할 수 있다.
  • @ControllerAdvice
    • @ControllerAdvice는 컨트롤러를 보조해주는 기능을 제공한다는 것을 명시한다.
    • @RestControllerAdvice public class ControllerSupport { @ExceptionHandler({NullPointerException.class, ClassCastException.class}) public String handle(Exception ex) { return "Exception Handle!!!"; } }
  • 컨트롤러 내부에 Exception을 처리하는 로직을 따로 작성하지 않아도 된다.

@RestControllerAdvice와 @ControllerAdvice의 차이는?

  • @ResponseBody의 유무 차이만 있을 뿐이다.

status code에도 어떤 에러인지 명시적으로 내어주고 싶은 경우에 @ResponseStatus를 사용할 수 있다.

@RestControllerAdvice
public class ControllerSupport {

    @ExceptionHandler({NullPointerException.class, ClassCastException.class})
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public String handle(Exception ex) {
        return "Exception Handle!!!";
    }
}

'Computer science > Spring' 카테고리의 다른 글

Stereo Type  (0) 2023.06.22
Spring Security  (0) 2023.06.21
@Transactional  (0) 2023.06.15
영속성 컨텍스트  (0) 2023.06.15
Filter 와 Interceptor  (0) 2023.06.15

+ Recent posts