Light Blue Pointer
본문 바로가기
Developing/개발일지

2023-12-04, Today I Learned

by Greedy 2023. 12. 4.

Spring 예외처리 방법 5가지

 

1) ResponseEntity 클래스를 사용

  1. @Getter
    @AllArgsConstructor
    public class RestApiException {
        private String errorMessage;
        private int statusCode;
    }
    
    public ResponseEntity<RestApiException> addFolders(@RequestBody FolderRequestDto folderRequestDto,
                                     @AuthenticationPrincipal UserDetailsImpl userDetails) {
        try {
            List<String> folderNames = folderRequestDto.getFolderNames();
    
            folderService.addFolders(folderNames, userDetails.getUser());
            return new ResponseEntity<>(HttpStatus.OK);
        } catch(IllegalArgumentException ex) {
            RestApiException restApiException = new RestApiException(ex.getMessage(), HttpStatus.BAD_REQUEST.value());
            return new ResponseEntity<>(
                    // HTTP body
                    restApiException,
                    // HTTP status code
                    HttpStatus.BAD_REQUEST);
        }
    }
    
  2.  
  3.  
  4. 2) @ExceptionHandler 사용
@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
    );
}

 

3) @RestControllerAdvice = @ControllerAdvice + @ResponseBody

모든 controller의 예외처리 한 곳에서

@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
        );
    }
}

 

4) messages.properties + messageSource.getMessage()

messages.properties를 만들고 메시지 찾아올 key값과 메시지 내용 value값을 써준다

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

Springboot 가 messageSource를 자동으로 Bean으로 등록해주기 때문에 Service에서 MessageSource 로 받아오면 됨

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);
}

messageSource.getMessage(param1,param2,param3)

param1 : messages.properties 파일에서 가져올 메시지의 키 값

param2 : 메시지 내에서 매개변수를 사용할 경우 전달하는 값

param3 : 언어 설정, Locale.getDefault() : 기본 언어 설정

 

@RestControllerAdvice 가 달린 클래스에 이거 추가해주면 만든 Exception쓸 수 있다

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

'Developing > 개발일지' 카테고리의 다른 글

2023-12-06, Today I Leanred  (2) 2023.12.06
2023-12-05, Today I Learned  (0) 2023.12.05
2023-11-30, Today I Learned  (0) 2023.11.30
2023-11-29, Today I Learned  (0) 2023.11.29
2023-11-28, Today I Learned  (0) 2023.11.28