-
[exception caching] 성능 향상을 위한 exception 처리Health-Genie 2024. 3. 21. 17:33728x90
예외처리에 대한 비용 문제를 공부하다가 기존에는 exception을 custom해서 사용했기에 성능쪽에서 괜찮겠지라는 생각했습니다.
내가 해논 예외 처리를 보니까 세분화 되어 있지도 않으며, 중복 코드도 있고 예외 비용이 낭비가 되고 있다는 것을 알게되었습니다.
아래와 같은 글을 읽으며 caching을 적용해 향상 시켜야겠다는 생각을 했습니다.
stackTrace를 가지지 않도록 오버라이딩한 Exception이라면 static final로 선언하여 일종의 상수 값 형태로 예외를 캐싱하고 쓰는 것이 매번 같은 종류의 예외를 new로 생성하는 것보다 효율적입니다.
https://moonsiri.tistory.com/174
기존 코드
[ GlobalExceptionHandler ]
@ExceptionHandler({CommonException.class}) public ResponseEntity<ErrorResponse> handleException(final CommonException exception) { log.warn("Exception occur: ", exception); return this.makeErrorResponseEntity(exception.getCommonErrorResult()); } private ResponseEntity<ErrorResponse> makeErrorResponseEntity(final CommonErrorResult errorResult) { return ResponseEntity.status(errorResult.getHttpStatus()) .body(new ErrorResponse(errorResult.name(), errorResult.getMessage())); }
[ CommonException ]
@Getter @RequiredArgsConstructor public class CommonException extends RuntimeException { private final CommonErrorResult commonErrorResult; }
[ CommonErrorResult ]
@Getter @RequiredArgsConstructor public enum CommonErrorResult { ALREADY_EXISTS_ROLE(HttpStatus.BAD_REQUEST, "already role exists"), USER_NOT_FOUND(HttpStatus.NOT_FOUND, "not found user"), ITEM_EMPTY(HttpStatus.BAD_REQUEST, "No items"), WRONG_VALIDATE_EMAIL(HttpStatus.BAD_REQUEST, "Wrong email validate"), VALID_OUT(HttpStatus.INTERNAL_SERVER_ERROR, "verification failed"), BAD_REQUEST(HttpStatus.BAD_REQUEST, "bad request"), UNABLE_TO_SEND_EMAIL(HttpStatus.BAD_REQUEST, "unable to send email"), WRONG_DOMAIN(HttpStatus.BAD_REQUEST, "domain is wrong for sending"), MEMBER_EXISTS(HttpStatus.BAD_REQUEST, "member already exists"), NO_SUCH_ALGORITHM(HttpStatus.BAD_REQUEST, "no such algorithm"), UNAUTHORIZED(HttpStatus.UNAUTHORIZED, "unauthorized"); private final HttpStatus httpStatus; private final String message; }
이런식의 코드를 가지고 매번 예외 처리를 할때 new를 사용해서 반환했기에 비용이 높았습니다.
[ 호출 방식 ]
throw new CommonException(CommonErrorResult.INVALID)
new 처리를 하지 않고 사용한 코드와 예시
[ CommonException ]
@Getter @RequiredArgsConstructor public class CommonException extends RuntimeException { private final HttpStatus httpStatus; private final String message; public static final CommonException ALREADY_EXISTS_ROLE = new CommonException(HttpStatus.BAD_REQUEST, "already role exists"); public static final CommonException ITEM_EMPTY = new CommonException(HttpStatus.BAD_REQUEST, "No items"); public static final CommonException USER_NOT_FOUND = new CommonException(HttpStatus.NOT_FOUND, "not found user"); public static final CommonException WRONG_VALIDATE_EMAIL = new CommonException(HttpStatus.BAD_REQUEST, "Wrong email validate"); public static final CommonException VALID_OUT = new CommonException(HttpStatus.INTERNAL_SERVER_ERROR, "verification failed"); public static final CommonException BAD_REQUEST = new CommonException(HttpStatus.BAD_REQUEST, "bad request"); public static final CommonException UNABLE_TO_SEND_EMAIL = new CommonException(HttpStatus.BAD_REQUEST, "unable to send email"); public static final CommonException WRONG_DOMAIN = new CommonException(HttpStatus.BAD_REQUEST, "domain is wrong for sending"); public static final CommonException MEMBER_EXISTS = new CommonException(HttpStatus.BAD_REQUEST, "member already exists"); public static final CommonException NO_SUCH_ALGORITHM = new CommonException(HttpStatus.BAD_REQUEST, "no such algorithm"); public static final CommonException UNAUTHORIZED = new CommonException(HttpStatus.UNAUTHORIZED, "unauthorized"); }
[ 호출 방법 ]
throw CommonException.BAD_REQUEST;
[ 3/22 수정 ]
[ GlobalExceptionHandler ]
@ExceptionHandler({JwtException.class}) public ResponseEntity<ErrorResponse> handleException(final JwtException exception) { log.warn("Exception occur: ", exception); return this.makeErrorResponseEntity(exception); } private ResponseEntity<ErrorResponse> makeErrorResponseEntity(final JwtException exception) { return ResponseEntity.status(exception.getHttpStatus()) .body(new ErrorResponse(exception.getHttpStatus().name(), exception.getMessage())); }
globla exception 처리를 하지 않으면 log에는 원하는대로 Message가 잘 나오지만, postman 혹은 브라우져에는 원하는대로 나오지 않는다.
- 장황한 에러 문구가 나오거나
- 401 같은 status code가 나옵니다
'Health-Genie' 카테고리의 다른 글
[Health-Genie] orElse() vs orElseGet() 차이 (2) 2024.03.06 무한스크롤 도입 (0) 2024.03.02 [모니터링] AWS - cloud watch 설정 (1) 2024.01.30 [CICD] 프로젝트 빌드 (2) 2024.01.25 [CICD] github actions CD ssh 연결안됨 (0) 2024.01.25