앱 간의 데이터 교환을 위한 REST 엔드포인트를 구축하고, 효율적인 응답 및 예외 관리 방법을 정리했습니다.
@ResponseBody: 메서드가 HTTP 응답을 직접 반환한다는 것을 디스패처 서블릿에 알립니다.@RestController: @Controller와 @ResponseBody를 합친 애너테이션입니다. 클래스 내 모든 메서드에 @ResponseBody가 적용되는 효과가 있습니다. @GetMapping("/all")
public List<Country> countries(){
Country c1 = Country.of("France",67);
Country c2 = Country.of("Spain",47);
return List.of(c1,c2);
}
@RestControllerAdvice): * 예외 처리 로직을 별도 클래스로 분리하여 전역적으로 관리합니다.@ExceptionHandler: 특정 예외가 발생했을 때 이를 가로챌 메서드를 지정(예외 핸들러)합니다.package com.example.spring_10.controllers;
import com.example.spring_10.exception.NotEnoughMoneyException;
import com.example.spring_10.model.ErrorDetails;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ExceptionControllerAdvice {
@ExceptionHandler(NotEnoughMoneyException.class)
public ResponseEntity<ErrorDetails> exceptionNotEnoughMoneyHandler(){
ErrorDetails errorDetails = new ErrorDetails();
errorDetails.setMessage("Not enough money to make the payment");
return ResponseEntity
.badRequest()
.body(errorDetails);
}
}
@RequestBody를 추가합니다.package com.example.spring_10.controllers;
import com.example.spring_10.exception.NotEnoughMoneyException;
import com.example.spring_10.model.ErrorDetails;
import com.example.spring_10.model.PaymentDetails;
import com.example.spring_10.services.PaymentService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.logging.Logger;
@RestController
public class PaymentController {
private final PaymentService paymentService;
public PaymentController(PaymentService paymentService) {
this.paymentService = paymentService;
}
private static Logger logger = Logger.getLogger(PaymentController.class.getName());
@PostMapping("/payment")
public ResponseEntity<PaymentDetails> makePayment(
@RequestBody PaymentDetails paymentDetails
){
logger.info("Receivced payment " + paymentDetails.getAmount());
return ResponseEntity
.status(HttpStatus.ACCEPTED)
.body(paymentDetails);
}
}
ResponseEntity를 사용하면 응답 상태와 헤더를 정교하게 제어할 수 있다.@RestControllerAdvice를 통해 비즈니스 로직(Service)과 예외 처리 로직을 깔끔하게 분리하자.@RequestBody와 JSON을 활용한다.#Spring #REST_API #RestController #DTO #GlobalExceptionHandler #백엔드공부