본문 바로가기

TIL

Error handler(예외처리의 경우)

게시판을 구현하면서 예외처리를 해주어야하는 부분이 있었다.

예를 들어 게시글에 댓글을 다는 경우 게시글의 ID (PK)가 존재 하지 않는경우 httpstatus만 넘어오고 message를 반환하지 않는 상황이 발생했다. 

ResponseEntity를 사용하여 객체를 응답의 객체를 직접 만들어 반환하여 해결하였다.

controller에서 Service로 postid와 댓글을 보낸다.

그다음 Service에서 postId를 가지고 Repository에서 해당 게시글이 있는지 찾는다.

없는경우 

Post post = postRepository.findById(postId).orElseThrow(

        ()-> {
            System.out.println("a");
            return new NotFoundException("포스트가 존재하지않습니다.");
        });

에러를 던져준다.

@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorResponse> notFound(Exception e) {

    return ResponseEntity
            .status(HttpStatus.NOT_FOUND)   // 404
            .body(
                    ErrorResponse.builder()
                            .message(e.getLocalizedMessage())               // 오류가 터진 곳에서 재정의한 메시지를 가져옴
                            .exceptionType(e.getClass().getSimpleName())    // Exception 타입을 반환 (Exception 종류가 많아지면 유용)
                            .build()
            );
}
package com.sparta.board.common.error;

public class NotFoundException extends RuntimeException {
    public NotFoundException(String message) {

        super(message);
    }
}

exceptionhandler에서 던져진 NotFoundException의 메세지를 가져와 ResponseEntity 객체를 생성하여 반환하여 client에게 반환해준다.

 

https://tecoble.techcourse.co.kr/post/2021-05-10-response-entity/

 

ResponseEntity - Spring Boot에서 Response를 만들자

웹 서비스에서는 많은 정보를 송수신하게 됩니다. 각각의 다른 웹 서비스들이 대화하려면, 서로 정해진 약속에 맞게 데이터를 가공해서 보내야합니다. 보내는 요청 및 데이터의 형식을 우리는 H

tecoble.techcourse.co.kr

 

'TIL' 카테고리의 다른 글

@Valid @NotEmpty  (0) 2022.02.18
IntelliJ 환경변수 설정  (0) 2022.02.18