Spring Exception Handler

박상우·2023년 7월 18일
0

Srping

목록 보기
4/5

Exception Handler

1. Exception Handler 란?

  • MVC 모델의 Controller Layer에서 발생하는 각종 Exception 예외에 대한 처리를 별도 Handler 클래스를 통해 유연하게 처리할 수 있도록 함
  • 단, Service, Repository(Persistence) 에 대한 예외처리는 각 레이어에서 처리해야 함

2. Exception Handler 사용법

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/account")
public class AccountApiController {

    @GetMapping("/me")
    public ApiResponse<AccountMeResponse> me() {
        AccountMeResponse data = AccountMeResponse.builder()
                .name("홍길동")
                .email("sad@gmail.com")
                .registeredAt(LocalDateTime.now())
                .build();

        try {
            String str = "안녕하세요";
            int i = Integer.parseInt(str);
        } catch (Exception e) {
            throw new IllegalStateException("사용자 me 호출시 에러 발생!");
        }

        return ApiResponse.OK(data);
    }
}
  • Controller 클래스에서 String -> Int 형으로 바꾸는 과정에서 발생하는 Exception을 IllegalStateException 예외 처리로 던짐
@Slf4j
@RestControllerAdvice
@Order(value = Integer.MIN_VALUE)
public class ApiExceptionHandler {

    @ExceptionHandler(value = IllegalStateException.class)
    public ResponseEntity<ApiResponse<Object>> apiException(ApiException apiException) {
        log.error("", apiException);

        ErrorCodeIfs errorCode = apiException.getErrorCodeIfs();
        
        return ResponseEntity
                .status(errorCode.getHttpStatusCode())
                .body(ApiResponse.ERROR(errorCode, apiException.getErrorDescription()));
    }
}
  • ApiExceptionHandler 라는 별도 클래스를 생성
  • @RestControllerAdvice 어노테이션을 사용하여 예외 처리에 대한 객체를 생성하여 리턴할 수 있도록 함
  • 단순 예외에 대해서만 처리하고 싶다면 @ControllerAdvice 어노테이션으로 사용
  • @ExceptionHandler 어노테이션을 사용하여 어떠한 예외 클래스에 대해서 처리할지 명시
  • 단, Controller, RestController에만 적용 가능

!! 예기치 못한 에러나 상황에 대한 로직 처리를 위해 예외 처리는 반드시 중요하다는 것을 명심해야 함

profile
보안, 개발을 같이 하고 있습니다

2개의 댓글

comment-user-thumbnail
2023년 7월 18일

소중한 정보 감사드립니다!

답글 달기
comment-user-thumbnail
2023년 7월 18일

정말 좋은 글 감사합니다!

답글 달기