본문 바로가기
스터디/Spring

[Spring] 스프링에서 특정 HTTP 응답코드 반환하기 (ResponseEntity, @ResponseStatus)

by zoodi 2025. 1. 17.
728x90

목차

  1. 1. Spring 에서 HTTP 응답상태 코드
  2. 2. ResponseEntity
  3. 3. @ResponseStatus 
  4. 4. ResponseStatusException 예외
  5. 5.참고자료

 

 

 

1. Spring 에서 HTTP 응답상태 코드

Spring은 HTTP 응답 상태 코드를 사용자 정의 할 수 있는 다음과 같은 방법을 제공합니다.

  • ResponseEntity 객체 응답
  • @ResponseStatus 어노테이션
  • ResponseStatusException 예외 발생

 

2. ResponseEntity

  • ResponseEntity 인스턴스와 함께 HTTP 응답 상태 코드를 전송할 수 있습니다.
  • 예시 코드
    • 요청을 통해서 전달 받은 Student 인스턴스를 생성하는 API가 있고, API를 호출했을 때 성공적으로 수행했을 때 Spring에서는 200 응답 코드를 보냅니다.
    • 요청을 통해서 전달 받은 Student 인스턴스를 생성하는 API에서 성공적으로 처리가 완료되면 201(CREATED) 응답을 보내고 싶을 때 ResponseEntity 객체를 통해서 다음과 같이 API를 작성할 수 있다.
@PostMapping("/students")
public ResponseEntity<Student> postStudent(@RequestBody Student student) {
    log.info("Request to create student: {}", student);
    Student newStudent = service.addNewStudent(student);
    return new ResponseEntity<>(student, HttpStatus.CREATED);
}

 

HTTP POST /students API를 호출하면 컨트롤러는 201 응답 코드를 반환합니다.

HTTP 응답 상태 코드 201은 서버에서 리소스가 생성되었음을 나타냅니다.

 

 

3. @ResponseStatus 

@ResponseStatus 어노테이션은

  • 컨트롤러나 예외 핸들러 메서드에 사용할 수 있습니다.
  • 예외 클래스에서 사용할 수 있습니다.
  • 예시코드
@ResponseStatus(
    value = HttpStatus.NOT_FOUND,
    reason = "Requested student does not exist"
)
public class StudentNotFoundException
    extends RuntimeException {
  
  public StudentNotFoundException(Throwable t) {
    super(t);
  }
}

위 코드를 적용하면 컨트롤러에서 StudentNotFoundException이 발생하면 Spring은 지정된 HTTP 응답 상태 코드(NOT FOUND)를 자동으로 반환합니다.

 

4. ResponseStatusException 예외

  • Spring은 컨트롤러가 특정 상태 코드 및 오류 메시지와 함께 던질 수 있는 ResponseStatusException을 제공합니다.
  • 예시코드
@PostMapping("/students")
public void postStudent(@RequestBody Student student) {
   
    log.info("Request to create student: {}", student);
    try {
        repository.save(student);
    } catch (InvalidStudentException e) {
        throw  new ResponseStatusException(HttpStatus.BAD_REQUEST);
    } catch (StudentServiceException e){
        throw  new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

 

정상적으로 동작하는 경우 Spring은 자동으로 200응답 코드를 전송합니다.

InvalidStudentException이 발생한 경우에는 BAD_REQUEST 응답 코드를 전송합니다.

StudentServiceException이 발생한 경우에는 INTERNAL_SERVER_ERROR 응답 코드를 전송합니다.

 

 

5.참고자료

https://devel-repository.tistory.com/57#google_vignette

728x90

댓글