Good Code - 서비스 메소드에 throws Exception 을 추가하지 말자 (feat. @Transactional)
희귀한 케이스지만, 가장 놓치기 쉬운 위험한 코드 패턴이다.
문제 상황
try {
var fileInfo = parseFileWithPresigned(uploadRequest.getUrl());
return InputFileInfo.builder()
.key(fileInfo.getKey())
.bucket(fileInfo.getBucket())
.fileMetadata(uploadRequest.getMetadata())
.build();
} catch (Exception e) {
log.info("외부 이미지로 판단하여 직접 다운로드 message: {}", e.getMessage());
return getFileWithDownload(type, uploadRequest);
}로직에서, 98% 는 Presigned URL 로 다운받지만
Presigned 로 받지 못하는 사용자를 위한 fallback 으로 이미지를 다운 받아 처리해주는 로직이 있다고 가정해보자.
public InputFileInfo getFileWithDownload(Type type, UploadRequest uploadRequest) throws InterruptedException, IOException {
...
}이 메소드는 IOException, InterruptedException 을 던진다.
호출하는 측이, 이 예외들을 잡고 처리해줄거라 기대했기 때문이다.
public InputFileInfo getInputFileInfo(UploadRequest uploadRequest, Type type) throws IOException, InterruptedException {
try {
var fileInfo = parseFileWithPresigned(uploadRequest.getUrl());
return InputFileInfo.builder()
.key(fileInfo.getKey())
.bucket(fileInfo.getBucket())
.fileMetadata(uploadRequest.getMetadata())
.build();
} catch (Exception e) {
log.info("외부 이미지로 판단하여 직접 다운로드 message: {}", e.getMessage());
return getFileWithDownload(type, uploadRequest);
}
}호출하는 측에서도 그대로 전파했다. (누군가는 잡아서 처리하겠지)
// 서비스 코드
public ResponseDto prompt(RequestDto requestDto, ClientDto clientDto) throws Exception {
...
// 요청으로 인한 크레딧 차감
var creditDto = creditService.applyCredit(clientDto, requestDto, clientInfo);
...
var fileInfo = fileService.getInputFileInfo(uploadRequest.getUrl());
...와 같이, 서비스 코드에서 throws Exception 이 선언되어있으면?
IOException 은 자연스럽게 Exception 에 포함되어 사라진다.
어차피 예외는
try {
service.request(requestDto, clientDto);
catch (Exception e) {
log.error("신규 요청중 오류남 request: {}", dto, e);
return ResponseEntity.status(500).build();
}
}Controller 에서 잡거나
ControllerAdvice 에서 잡으니까 괜찮은거 아닌가? 라고 생각한다.
하지만, Spring 을 사용하는 입장에선 치명적인 문제가 존재한다.
Spring 에서 Transactional 을 처리하는 방법 때문이다.
Transaction in Spring
이미 너무 많은 곳에서 설명을 해서 자세한 내용은 생략한다.
By contrast, a checked exception is considered a business exception and therefore a regular expected outcome of the transactional business method, i.e. a kind of alternative return value which still allows for regular completion of resource operations.checked exception 은 비즈니스 중 발생한 예외라고 간주하고, 트랜잭션 비즈니스 메소드의 정상적으로 예상된 결과이며, 리소스 작업이 정상 허용되는걸 여전히 허용한다.
이는, EJB 부터 내려온 전통적인 규칙이라고 한다..
(현재는, 의도가 많이 바뀌어버린거 같긴 하지만)
// 요청으로 인한 크레딧 차감
var creditDto = creditService.applyCredit(clientDto, requestDto, clientInfo);그래서, 크레딧이 롤백 될거라 기대하지만 DB 에 남아서 차감이 된다.
해결
당연하게도, throws Exception 을 지양하자.
메소드를 깔끔하게 해주는것처럼 보이지만, 이는 Sugar Code 이자 그 미래의 어떤 변화에도 위험하게 만든다.