2023-02-12-TIL
2023-02-12-TIL
Today I Learned
Error Code with Enum
에러를 공통 포맷으로 내려 주고, 에러 코드 목록을 한곳에서 관리하기 위해 enum을 쓰는 방법이다. 참고한 글의 예시는 HTTP 상태, 자체 에러 코드, 메시지를 필드로 가진 ErrorCode enum을 만들고, 예외가 이 enum을 들고 다니게 한다.
1
2
3
4
5
6
7
8
9
10
@Getter
@RequiredArgsConstructor
public enum ErrorCode {
INVALID_INPUT(400, "C001", "Invalid input"),
RESOURCE_NOT_FOUND(404, "C002", "Resource not found");
private final int status;
private final String code;
private final String message;
}
코드 값이 enum 상수로 모여 있으니 중복을 피하기 쉽고, 어떤 코드가 어디에 쓰이는지 IDE로 바로 추적할 수 있다. 함께 저장한 Stack Overflow 질문은 enum 안에서 예외를 던졌는데 @ExceptionHandler로 흐름이 오지 않는 문제를 다룬다. 예외가 컨트롤러 요청 처리 흐름 안에서 던져져야 핸들러가 잡을 수 있다는 점을 기억해 둔다.
- https://stackoverflow.com/questions/72745698/throwing-custom-exception-inside-enum-but-flow-is-not-coming-to-exceptionhandle
- https://velog.io/@waldo/%EC%97%90%EB%9F%AC%EC%B2%98%EB%A6%AC101-Enum%EC%9C%BC%EB%A1%9C-%EC%97%90%EB%9F%AC%EC%BD%94%EB%93%9C-%EA%B4%80%EB%A6%AC%ED%95%98%EA%B8%B0
Error Handling with Spring Boot
Spring 블로그의 “Exception Handling in Spring MVC”는 처리 방법을 세 단계로 정리한다. 예외 클래스에 @ResponseStatus를 붙여 상태 코드를 지정하는 방법, 컨트롤러 안에 @ExceptionHandler 메서드를 두는 방법, @ControllerAdvice로 여러 컨트롤러의 예외를 한곳에서 처리하는 방법이다. Toptal 글은 여기에 더해 ApiError 같은 응답 클래스를 정의하고, ResponseEntityExceptionHandler를 상속한 전역 핸들러에서 모든 예외를 이 형식으로 바꾸는 구성을 보여 준다.
컨트롤러가 성공과 실패에 서로 다른 타입을 돌려줘야 할 때는 ResponseEntity<?>로 반환 타입을 넓히기보다, 정상 응답만 컨트롤러에서 반환하고 실패는 예외로 던져 전역 핸들러가 에러 응답을 만들게 하는 편이 정리하기 쉽다.
- https://stackoverflow.com/questions/38117717/what-is-the-best-way-to-return-different-types-of-responseentity-in-spring-boot
- https://www.toptal.com/java/spring-boot-rest-api-error-handling
- https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
Custom Error Response
에러 응답 형식을 설계할 때 공개 API들이 어떻게 하는지 비교해 보았다. Google Calendar API는 HTTP 상태 코드와 함께 아래 같은 JSON 본문을 돌려준다. 최상위에 code와 message가 있고, errors 배열에 domain, reason, message로 세부 원인을 담는다. 같은 400이라도 reason으로 원인을 구분할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"error": {
"errors": [
{
"domain": "calendar",
"reason": "timeRangeEmpty",
"message": "The specified time range is empty.",
"locationType": "parameter",
"location": "timeMax"
}
],
"code": 400,
"message": "The specified time range is empty."
}
}
카카오 디벨로퍼스 문서도 API마다 공통 에러 코드 표를 따로 두고 응답 본문에 서비스 고유 코드를 담는다. 다만 저장해 둔 카카오 레퍼런스의 에러 코드 링크는 지금 404를 반환한다. Cloudflare의 Custom Errors는 성격이 다른데, 원본 서버나 Cloudflare에서 400 이상의 HTTP 에러가 났을 때 방문자에게 보여 줄 에러 페이지나 응답 내용을 바꾸는 기능이다.
정리하면 HTTP 상태 코드는 큰 분류로 쓰고, 클라이언트가 분기할 세부 원인은 본문의 코드 필드로 주며, 사람이 읽을 메시지는 따로 두는 구성이 공통적이다.
- https://developers.cloudflare.com/rules/custom-error-responses/
- https://developers.kakao.com/docs/latest/ko/talkcalendar/common
- https://apis.map.kakao.com/web/documentation/
- https://developers.kakao.com/docs/latest/ko/talkcalendar/rest-api#calendar-get-list
- https://developers.kakao.com/docs/latest/ko/reference/rest-api-reference#error-code
- https://developers.google.com/calendar/api/guides/errors
- https://developers.google.com/calendar/api/v3/reference/acl/get?hl=ko
- https://developers.google.com/calendar/api/v3/reference/acl#resource
댓글
아직 댓글이 없습니다