Response
package com.example.mentoring.Response;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.sun.net.httpserver.Authenticator;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
@JsonInclude(JsonInclude.Include.NON_NULL)// Null 버림
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Getter
public class Response {
private boolean success;
private int code;
private Result result;
// 데이터 없이 성공 반환
public static Response success(){
return new Response(true,0,null);
}
// 데이터 포함해서 성공 반환
public static <T> Response success(T data){
return new Response(true,0,new Success<>(data));
}
// 에러 발생시 반환해주는 경우
public static Response failure(int code, String msg){
return new Response(false, code, new Failure(msg));
}
}
Result
package com.example.mentoring.Response;
interface Result {
}
Success
package com.example.mentoring.Response;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Getter;
@JsonInclude(JsonInclude.Include.NON_NULL)
//null값을 가지는 필드는 JSON응답에 포함되지 않음
@Getter
@AllArgsConstructor
public class Success<T> implements Result {
private T data; // T는 어떤 타입이 와도 상관없음을 의미
}
Failure
package com.example.mentoring.Response;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class Failure implements Result{
private String msg;
}
Exception
WriterNotFoundException : 작성자 예외처리
public class WriterNotFoundException extends RuntimeException{
}
BoardNotFoundException : 게시글 예외처리
public class BoardNotFoundException extends RuntimeException{
}
ExceptionAdvice
package com.example.mentoring.advice;
import com.example.mentoring.Response.Response;
import com.example.mentoring.exception.BoardNotFoundException;
import com.example.mentoring.exception.WriterNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice // @RestController + @Advice
//ExceptionAdvice == Exception을 관리하기 위한 통제소 == 실패할 경우 실패 메세지를 보내기 위한 RestController
public class ExceptionAdvice {
//404 NotFound Error
@ExceptionHandler(BoardNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Response boardNotFoundException(){
return Response.failure(404,"게시글을 찾을 수 없습니다.");
}
// 404 NotFound
@ExceptionHandler(WriterNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Response writerNotFoundException(){
return Response.failure(404, "작성자를 입력해주세요.");
}
}
BoardController
package com.example.mentoring.controller;
import com.example.mentoring.Response.Response;
import com.example.mentoring.entity.Board;
import com.example.mentoring.service.BoardService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController //RestAPI 서버
@RequiredArgsConstructor //@Non null + static 생성자
public class BoardController {
private final BoardService boardService;
@ResponseStatus(HttpStatus.OK)
@GetMapping("/boards")
public Response getBoards(){
return Response.success(boardService.getBoards());
}
@ResponseStatus(HttpStatus.OK)
@GetMapping("/boards/{id}")
public Response getBoard(@PathVariable("id") Long id){
return Response.success(boardService.getBoard(id));
}
@ResponseStatus(HttpStatus.OK)
@PostMapping("/boards")
public Response editBoard(@PathVariable("id") Long id, @RequestBody Board updateBoard){
return Response.success(boardService.editBoard(id,updateBoard));
}
@ResponseStatus(HttpStatus.OK)
@PutMapping("/boards/{id}")
public Response editBoard(@PathVariable("id") Long id, @RequestBody Board updateBoard){
return Response.success(boardService.editBoard(id,updateBoard));
}
@ResponseStatus(HttpStatus.OK)
@DeleteMapping("/api/boards/{id}")
public Response deleteBoard(@PathVariable("id") Long id){
boardService.deleteBoard(id);
return Response.success("삭제 완료");
}
BoardRepository
Board board = boardRepository.findById(id).get();에서
예외처리를 추가하였기에 이렇게 코드를 수정해준다.
Board board = boardRepository.findById(id).orElseThrow(BoardNotFoundException::new);
이 코드로 인해, 어떤 오류가 발생했는지 알 수 있게 된다.
'Java > Spring' 카테고리의 다른 글
SpringBoot JPA(Java Persistence API) 사용 목적 (0) | 2022.08.05 |
---|---|
DTO, DAO, Repository, Entity 개념 (0) | 2022.08.04 |
스프링 스터디(RestAPI의 다양한 기능 추가(Exception, Response..) (0) | 2022.07.25 |
스프링 스터디(3주차) CRUD 게시판 만들기 + Postman 사용 (0) | 2022.07.20 |
스프링 스터디(2주차) + 내용 정리 (0) | 2022.07.12 |