티스토리 뷰

JPA

글 목록 조회 API 만들기

yoooon1212 2024. 10. 2. 14:16
BlogService 코드 추가
	// 전체 게시글 조회 기능 
	public List<Article> findAll() {
		List<Article> articles = postRepository.findAll();
		// ListCrudRepository가 findAll() 제공
		return articles;
	}

 

ApiUtil

공통 응답 DTO 생성
package com.example.demo.common;

import lombok.Data;

@Data
public class ApiUtil<T> {

	private Integer status;// 응답 상태 코드 저장(200, 400, 500)
	private String msg; // 응답 메시지 저장(성공, 실패 문자열)
	// 변수명은 동일하나 데이터 타입이 달라져야 할 때 -> 제네릭 클래스 설계
	private T body; // 응답의 실제 데이터 저장(제네릭 활용)
	
	// 성공적인 응답을 반환할 때 사용하는 생성자 
	public ApiUtil(T body) {
		// 하드 코딩으로 받음
		this.status = 200; // 통신 성공
		this.msg = "성공";
		this.body = body;
	}
	
	// 커스텀 상태 코드와 메시지를 반환시킬 때 사용하는 생성자(예: 에러 응답)
	public ApiUtil(Integer status, String msg) {
		this.status = status;
		this.msg = msg;
		this.body = null;
	}
}

 

 

BlogApiController 코드 추가
	// URL , 즉, 주소 설계 - http://localhost:8080/api/articles
	@GetMapping(value = "/api/articles", produces = MediaType.APPLICATION_JSON_VALUE)
	public ApiUtil<List<Article>>  getAllArticles() {
		List<Article> articles = blogService.findAll();
		if(articles.isEmpty()) {
			return new ApiUtil<>(204, "조회된 게시글이 없습니다");
		}
		return new ApiUtil<>(articles);
	}

 

 

ExceptionHandler 생성

 

 

 

사용자 정의 예외 클래스 생성
package com.example.demo.common.errors;

public class Exception400 extends RuntimeException {

	public Exception400(String msg) {
		super(msg); // 부모 클래스에 만들어져 있으므로 넘겨주기
	}
}

 

 

MyExceptionHandler 생성
package com.example.demo.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.example.demo.common.errors.Exception400;
import com.example.demo.common.errors.Exception401;
import com.example.demo.common.errors.Exception403;
import com.example.demo.common.errors.Exception404;
import com.example.demo.common.errors.Exception500;

// RuntimeException 터지면 해당 파일로 오류가 모인다. 
@RestControllerAdvice // IoC
// @ControllerAdvice -> 뷰 에러 페이지
// @RestControllerAdvice -> 데이터 반환(에러)
public class MyExceptionHandler {

	private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);

	@ExceptionHandler(Exception400.class)
	public ResponseEntity<ApiUtil<Object>> ex400(Exception400 e) {
		logger.error("400 Error: {}", e.getMessage());
		ApiUtil<Object> apiUtil = new ApiUtil<>(400, e.getMessage());
		return new ResponseEntity<>(apiUtil, HttpStatus.BAD_REQUEST);
	}

	@ExceptionHandler(Exception401.class)
	public ResponseEntity<ApiUtil<Object>> ex401(Exception401 e) {
		logger.error("401 Error: {}", e.getMessage());
		ApiUtil<Object> apiUtil = new ApiUtil<>(401, e.getMessage());
		return new ResponseEntity<>(apiUtil, HttpStatus.UNAUTHORIZED);
	}

	@ExceptionHandler(Exception403.class)
	public ResponseEntity<ApiUtil<Object>> ex403(Exception403 e) {
		logger.error("403 Error: {}", e.getMessage());
		ApiUtil<Object> apiUtil = new ApiUtil<>(403, e.getMessage());
		return new ResponseEntity<>(apiUtil, HttpStatus.FORBIDDEN);
	}

	@ExceptionHandler(Exception404.class)
	public ResponseEntity<ApiUtil<Object>> ex404(Exception404 e) {
		logger.error("404 Error: {}", e.getMessage());
		ApiUtil<Object> apiUtil = new ApiUtil<>(404, e.getMessage());
		return new ResponseEntity<>(apiUtil, HttpStatus.NOT_FOUND);
	}

	@ExceptionHandler(Exception500.class)
	public ResponseEntity<ApiUtil<Object>> ex500(Exception500 e) {
		logger.error("500 Error: {}", e.getMessage());
		ApiUtil<Object> apiUtil = new ApiUtil<>(500, e.getMessage());
		return new ResponseEntity<>(apiUtil, HttpStatus.INTERNAL_SERVER_ERROR);
	}
}

 

 

BlogApiController 추가한 코드 수정하기
@GetMapping("/api/articles")
	public ApiUtil<?> getAllArticles() { // 값 받을 거 없음
		List<Article> articles = blogService.findAll();
		if(articles.isEmpty()) {
			// return new ApiUtil<>(new Exception400("게시글이 없습니다."));
			throw new Exception400("게시글이 없습니다.");
		}
		return new ApiUtil<>(articles);
	}

 

콘솔창 결과

'JPA' 카테고리의 다른 글

글 수정 API 만들기  (0) 2024.10.02
글 상세보기(조회) API 구현  (0) 2024.10.02
블로그 서비스, 컨트롤러 만들기  (0) 2024.10.02
블로그 레포지토리 만들기  (0) 2024.10.02
블로그 엔티티 만들기  (0) 2024.10.01
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함