스프링

HttpStatus란

148june 2025. 4. 28. 15:49

https://developer.mozilla.org/ko/docs/Web/HTTP/Reference/Status
참고할만한 링크


🌐 HttpStatus란?

HttpStatus는 서버가 클라이언트 요청에 대해 응답할 때 보내는 상태 코드야.
상태 코드를 통해 요청이 성공했는지, 실패했는지, 추가 조치가 필요한지 등을 알려준다.

상태 코드는 항상 3자리 숫자로 되어 있고, 숫자 범위에 따라 의미가 다르다.


🔢 HttpStatus 분류

범위 의미 설명
1xx 정보 요청을 받았고 계속 처리 중
2xx 성공 요청이 성공적으로 처리됨
3xx 리다이렉션 다른 위치로 이동 필요
4xx 클라이언트 오류 요청이 잘못됨 (클라이언트 문제)
5xx 서버 오류 서버가 요청 처리 실패 (서버 문제)

🏷️ 주요 HttpStatus 코드 + 예시

✅ 200 OK

  • 설명: 요청이 정상적으로 성공했다.
  • 예시:
@GetMapping("/hello")
public ResponseEntity<String> hello() {
    return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}

요청 성공 시, 200 OK 상태와 함께 "Hello World!"를 반환한다.


✅ 201 Created

  • 설명: 요청 성공 + 새로운 리소스가 생성됨.
  • 예시:
@PostMapping("/users")
public ResponseEntity<String> createUser() {
    return new ResponseEntity<>("User created!", HttpStatus.CREATED);
}

새로운 유저를 만들었을 때, 201 Created를 반환.


⚠️ 400 Bad Request

  • 설명: 클라이언트가 잘못된 요청을 보냈다.
  • 예시:
@GetMapping("/users")
public ResponseEntity<String> getUser(@RequestParam(required = false) String id) {
    if (id == null) {
        return new ResponseEntity<>("Missing ID", HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>("User found", HttpStatus.OK);
}

필수 파라미터 id가 없으면 400 Bad Request 반환.


🚫 401 Unauthorized

  • 설명: 인증이 필요하거나 인증 실패.
  • 예시:
@GetMapping("/private")
public ResponseEntity<String> privatePage(@RequestHeader(value = "Authorization", required = false) String token) {
    if (token == null) {
        return new ResponseEntity<>("Unauthorized", HttpStatus.UNAUTHORIZED);
    }
    return new ResponseEntity<>("Welcome!", HttpStatus.OK);
}

Authorization 헤더가 없으면 401 Unauthorized 반환.


❌ 404 Not Found

  • 설명: 요청한 리소스가 존재하지 않는다.
  • 예시:
@GetMapping("/products/{id}")
public ResponseEntity<String> getProduct(@PathVariable String id) {
    if (!productExists(id)) {
        return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<>("Product details", HttpStatus.OK);
}

private boolean productExists(String id) {
    return false; // 예시용
}

존재하지 않는 상품 ID를 요청하면 404 Not Found 반환.


💥 500 Internal Server Error

  • 설명: 서버 내부 오류로 요청을 처리할 수 없음.
  • 예시:
@GetMapping("/error")
public ResponseEntity<String> serverError() {
    throw new RuntimeException("Unexpected server error!");
}

런타임 에러가 발생하면 기본적으로 500 Internal Server Error가 반환된다.


✨ 정리

  • 2xx: 성공
  • 4xx: 클라이언트 문제
  • 5xx: 서버 문제
  • Spring에서는 ResponseEntity로 직접 상태코드를 설정하거나, @ResponseStatus로 예외에 붙여줄 수 있다.

'스프링' 카테고리의 다른 글

KPT 회고  (0) 2025.04.29
트러블슈팅 JWT와 @AuthenticationPrincipal의 차이점  (0) 2025.04.28
도커 설정  (0) 2025.04.22
@ExtendWith(SpringExtension.class) vs @ExtendWith(MockitoExtension.class)  (0) 2025.04.18
프록시  (0) 2025.04.18