1. 현재 응답의 문제점

지금 우리 API의 응답을 보면:

성공 시:

{
    "id": 1,
    "title": "제목",
    "content": "내용",
    "author": "홍길동",
    "createdAt": "2026-03-05T15:30:00"
}

실패 시 (존재하지 않는 게시글):

{
    "timestamp": "2026-03-05T06:30:00.000+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "path": "/api/posts/999"
}

문제가 세 가지 있습니다.

첫째, 성공과 실패의 응답 구조가 다릅니다. React에서 API를 호출할 때 성공인지 실패인지에 따라 완전히 다른 파싱 로직을 써야 합니다.

둘째, 에러 메시지가 불친절합니다. "Internal Server Error"만으로는 무엇이 잘못됐는지 알 수 없습니다.

셋째, 상태 코드가 부정확합니다. 게시글이 없는 건 404여야 하는데 500이 나옵니다.


2. ResponseEntity 심화

먼저 ResponseEntity를 좀 더 깊이 이해합시다. ResponseEntity는 상태 코드 + 헤더 + 바디를 모두 제어할 수 있는 응답 객체입니다.

구조

ResponseEntity<T>
├── HttpStatus (상태 코드)
├── HttpHeaders (응답 헤더)
└── T body (응답 바디)

자주 쓰는 생성 방법

// 200 OK + 바디
ResponseEntity.ok(body)

// 201 Created + 바디
ResponseEntity.status(HttpStatus.CREATED).body(body)

// 204 No Content (바디 없음)
ResponseEntity.noContent().build()

// 404 Not Found (바디 없음)
ResponseEntity.notFound().build()

// 커스텀 헤더 추가
ResponseEntity.ok()
        .header("X-Custom-Header", "value")
        .body(body)

제네릭 타입

ResponseEntity<T>T는 바디의 타입입니다:

ResponseEntity<PostResponse>           // 바디가 PostResponse
ResponseEntity<List<PostResponse>>     // 바디가 리스트
ResponseEntity<Void>                   // 바디 없음 (삭제 등)
ResponseEntity<Map<String, String>>    // 바디가 Map