[SPRING] Global 예외처리

kang·2024년 9월 26일

SPRING

목록 보기
21/22


@ControllerAdvice 사용

  • Spring에서 예외처리를 위한 클래스 레벨 애너테이션

사용하는 이유?

  • 예외처리 중앙집중화(관리편함)
  • 코드 중복 방지
  • @RestControllerAdvice
    • @ControllerAdvice + @ResponseBody
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({IllegalArgumentException.class})
    public ResponseEntity<RestApiException> handleException(IllegalArgumentException ex) {
        RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
        return new ResponseEntity<>(
                // HTTP body
                restApiException,
                // HTTP status code
                HttpStatus.BAD_REQUEST
        );
    }
}

Error 메시지 관리하기

  • Spring의 properties 파일을 이용한 에러 메시지 관리

-> resources > messages.properties

below.min.my.price=최저 희망가는 최소 {0}원 이상으로 설정해 주세요.
not.found.product=해당 상품이 존재하지 않습니다.
private final MessageSource messageSource;

...

@Transactional
public ProductResponseDto updateProduct(Long id, ProductMypriceRequestDto requestDto) {
    int myprice = requestDto.getMyprice();
    if (myprice < MIN_MY_PRICE) {
        throw new IllegalArgumentException(messageSource.getMessage(
                "below.min.my.price",
                new Integer[]{MIN_MY_PRICE},
                "Wrong Price",
                Locale.getDefault()
        ));
    }

    Product product = productRepository.findById(id).orElseThrow(() ->
            new ProductNotFoundException(messageSource.getMessage(
                    "not.found.product",
                    null,
                    "Not Found Product",
                    Locale.getDefault()
            ))
    );

    product.update(requestDto);

    return new ProductResponseDto(product);
}
profile
뉴비 개발 공부중

0개의 댓글