ResponseEntity
Spring에서 ResponseEntity는 HTTP 응답을 표현하는 클래스다. 이 클래스는 HTTP 상태 코드, 헤더, 본문(body) 등을 포함하여 클라이언트에게 반환할 응답을 구성하는 데 사용된다. ResponseEntity를 사용하면 보다 유연하고 세밀한 HTTP 응답 처리가 가능하다.
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/example")
public ResponseEntity<String> getExample() {
String responseBody = "Hello, World!";
return ResponseEntity.ok()
.header("Custom-Header", "value")
.body(responseBody);
}
}
ResponseEntity.ok(): 200 OK 상태 코드와 함께 응답을 생성한다.ResponseEntity.badRequest(): 400 Bad Request 상태 코드와 함께 응답을 생성한다.ResponseEntity.notFound(): 404 Not Found 상태 코드와 함께 응답을 생성한다.ResponseEntity.status(HttpStatus): 특정 상태 코드와 함께 응답을 생성한다.이처럼 ResponseEntity는 RESTful API를 개발할 때 매우 유용한 도구다.
@ExceptionHandler
@ExceptionHandler는 Spring 프레임워크에서 예외를 처리하기 위한 어노테이션이다. 이 어노테이션을 사용하면 특정 예외가 발생했을 때 해당 예외를 처리하는 메서드를 정의할 수 있다. 이를 통해 애플리케이션의 오류 처리를 중앙 집중화하고, 사용자에게 더 나은 오류 메시지를 제공할 수 있다.
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NullPointerException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleNullPointerException(NullPointerException ex) {
// 로그 기록 또는 사용자에게 보여줄 메시지 처리
return "error/nullPointerError"; // 에러 페이지의 뷰 이름
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleGeneralException(Exception ex) {
// 일반 예외 처리
return "error/generalError"; // 에러 페이지의 뷰 이름
}
}
@ControllerAdvice와 함께 사용하면 모든 컨트롤러에서 발생하는 예외를 처리할 수 있다.@ResponseStatus를 사용하여 클라이언트에 반환할 HTTP 상태 코드를 지정할 수 있다.