강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

비가싫어요님의 프로필 이미지
비가싫어요

작성한 질문수

SpringBoot 예외처리와 관련하여 질문드립니다.

작성

·

142

0

예외처리에 관해서 공부하고 있는 취준생입니다. 공부 중 막히는 부분이 있어 질문을 하고자 합니다.

 

우선 제 코드를 보여드리겠습니다. 코드는 이곳에서 참고해서 따라하고 있습니다.

 

Custom 예외를 만들 ErrorCode 클래스

@Getter
@AllArgsConstructor
public enum ApiErrorCode {

   // 400번대 에러: 클라이언트에서의 잘못된 요청
   MEMBER_NOT_FOUND(NOT_FOUND, "멤버를 찾을 수 없습니다."),


   // 500번대 에러: 서버 내부에서의 에러 발생
   SYSTEM_ERROR(INTERNAL_SERVER_ERROR, "시스템 내부 오류입니다.");


   private final HttpStatus httpStatus;
   private final String detail;
}

예외 응답하는 클래스

@Getter
@Builder
public class ApiErrorResponse {

   private final int status;
   private final String error;
   private final String errorCode;
   private final String errorMessage;

   public static ResponseEntity<ApiErrorResponse> toResponseEntity(ApiErrorCode apiErrorCode) {
      return ResponseEntity
         .status(apiErrorCode.getHttpStatus())
         .body(
            ApiErrorResponse.builder()
               .status(apiErrorCode.getHttpStatus().value())
               .error(apiErrorCode.getHttpStatus().name())
               .errorCode(apiErrorCode.name())
               .errorMessage(apiErrorCode.getDetail())
               .build()
         );
   }
}

 

예외를 발생시킬 클래스

@Getter
@AllArgsConstructor
public class ApiException extends RuntimeException {

   private final ApiErrorCode apiErrorCode;
}

 

@RestControllerAdvice

@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

   @ExceptionHandler(value = {ApiException.class})
   protected ResponseEntity<ApiErrorResponse> handleApiException(ApiException e) {
      return ApiErrorResponse.toResponseEntity(e.getApiErrorCode());
   }
}

 

@Service

@Service
@RequiredArgsConstructor
public class MemberService {

   private final MemberRepository memberRepository;

   BasicResponse basicResponse = new BasicResponse();

   // Member 하나 조회
   public BasicResponse findMember(Long memberId) {

      Optional<Member> member = memberRepository.findById(memberId);

      if (member.isPresent()) {
         basicResponse = BasicResponse.builder()
            .code(HttpStatus.OK.value())
            .httpStatus(HttpStatus.OK)
            .message("Member 조회에 성공하였습니다.")
            .result(Arrays.asList(member.get()))
            .build();
      } else {
         throw new ApiException(ApiErrorCode.MEMBER_NOT_FOUND);
      }

      return basicResponse;
   }

 

포스트맨으로 예외 발생시켰을 때 결과 화면

예외 화면.png

 

제가 궁금한 것은 예외가 발생했을 때 Response에 넣어주는 객체에 현재 어떤 요청 url에 대하여 예외가 발생했는지를 알려주기 위해 path를 넣고 싶은데 이것을 어떻게 하면 좋을지입니다.

 

도움 주시면 감사하겠습니다.

답변

답변을 기다리고 있는 질문이에요
첫번째 답변을 남겨보세요!
비가싫어요님의 프로필 이미지
비가싫어요

작성한 질문수

질문하기