본문 바로가기
개인 프로젝트

예외 처리 시, @JsonInclude의 쓰임 정리

by 쿠키오빠 2025. 6. 10.
반응형

 

 

존재하지 않는 게시글 조회 시, 예외 처리 테스트를 진행했다.

@Test
@DisplayName("존재하지 않는 게시글 조회")
void test9 () throws Exception {
    mockMvc.perform(get("/post/{postId}", 1L)
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isNotFound())
            .andDo(print());
}

 

<응답 전용 ErrorResponse>

@Getter
public class ErrorResponse {

    private final String code;
    private final String message;

    private Map<String, String> validation = new HashMap<>();

    public void addValidation(String fieldName , String errorMessage) {
        this.validation.put(fieldName,errorMessage);
    }

    @Builder
    public ErrorResponse(String code, String message) {
        this.code = code;
        this.message = message;
    }
}

 

반환 값은 code , message , validation이고, 

 

필드별 에러 정보가 없기 때문에 당연히 validation은 null이다.

 

만약 클라이언트가 공백인 validation을 포함하지 말고 JSON 형식으로 응답을 해달라는 요청을 한다면 

@JsonInclude 를 사용하면 된다.

 


@JsonInclude은 Jackson 라이브러리에서 JSON 직렬화 시 포함할 속성의 조건을 지정할 수 있게 해주고, 특정 필드가 null이거나 기본값이면 JSON 출력에서 제외할 수 있도록 설정 가능한 어노테이션이다.

< JsonInclude의 옵션 정리 >

ALWAYS 항상 포함 (기본값) 모든 필드가 JSON에 포함됨
NON_NULL null인 필드는 제외 null 값은 JSON 출력에서 생략
NON_ABSENT Optional.empty() 등 Absent 상태 제외 (Optional, AtomicReference 등) Java 8 이상에서 사용 권장
NON_EMPTY null, 빈 컬렉션([]), 빈 문자열("") 등 "비어 있음" 상태일 경우 제외 불필요한 빈 값 제거에 유용
NON_DEFAULT 기본값(예: int는 0, boolean은 false 등)과 같은 값은 제외 불필요한 기본값 생략
USE_DEFAULTS Jackson의 기본 동작을 사용 (ALWAYS) 명시적으로 기본 포함 동작을 지정하고자 할 때

 

나는 비어 있는 validation을 응답하지 않기 위해 NON_EMPTY를 사용해 보았다.


 

 

@JsonInclude(value = JsonInclude.Include.NON_EMPTY) 적용 전


@JsonInclude(value = JsonInclude.Include.NON_EMPTY) 적용 후

// 응답 전용 클래스
@Getter
@JsonInclude(value = JsonInclude.Include.NON_EMPTY)
public class ErrorResponse {

    private final String code;
    private final String message;

    private Map<String, String> validation = new HashMap<>();

    public void addValidation(String fieldName , String errorMessage) {
        this.validation.put(fieldName,errorMessage);
    }

    @Builder
    public ErrorResponse(String code, String message) {
        this.code = code;
        this.message = message;
    }
}

 

<응답>

 

 


JsonInclude를 굳이 사용할 필요는 없다고 생각하지만, 알아두면 추후 클라이언트의 요청에 정확하게 대응할 수 있지 않을까 싶다.

반응형

'개인 프로젝트' 카테고리의 다른 글

생성자 말고 Lombok / @Builder 활용하기  (0) 2025.05.27