-
최종 프로젝트 개발3엘리스트랙 2024. 4. 28. 14:53728x90
에러처리를 할 때 한 번에 처리해 주기 위해 예외처리 코드를 넣어주었다.
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ServiceLogicException.class) public ResponseEntity<Object> handleServiceLogicException(ServiceLogicException ex) { ExceptionCode code = ex.getExceptionCode(); ErrorResponse errorResponse = new ErrorResponse(code.getStatus(), ex.getMessage()); return new ResponseEntity<>(errorResponse, code.getStatus()); } // ErrorResponse 클래스 (내부 클래스로 정의) @Getter private static class ErrorResponse { // Getters private final HttpStatus status; private final String message; public ErrorResponse(HttpStatus status, String message) { this.status = status; this.message = message; } } // MethodArgumentNotValidException 처리 @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex) { // 오류 메시지를 담을 Map 생성 Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getAllErrors().forEach(error -> { String fieldName = ((FieldError) error).getField(); String errorMessage = error.getDefaultMessage(); errors.put(fieldName, errorMessage); }); // 상태 코드 400(Bad Request)와 함께 오류 메시지를 반환 return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); } }
@Getter public class ServiceLogicException extends RuntimeException { private final ExceptionCode exceptionCode; public ServiceLogicException(ExceptionCode exceptionCode) { super(exceptionCode.getMessage()); this.exceptionCode = exceptionCode; } }
@Getter public enum ExceptionCode { USER_NOT_FOUND(HttpStatus.NOT_FOUND, "존재하지 않는 회원입니다."), USER_ALREADY_EXISTS(HttpStatus.CONFLICT, "이미 존재하는 회원입니다."), CATEGORY_NOT_FOUND(HttpStatus.NOT_FOUND, "존재하지 않는 카테고리입니다."), CATEGORY_ALREADY_EXISTS(HttpStatus.CONFLICT, "이미 존재하는 카테고리입니다."), MEETING_NOT_FOUND(HttpStatus.NOT_FOUND, "모임을 찾을 수 없습니다."), ALREADY_PARTICIPATING(HttpStatus.CONFLICT, "이미 참여중인 모임입니다" ), ALREADY_PARTICIPATING_ON_DATE(HttpStatus.CONFLICT, "참여중인 날짜입니다." ), USERMOUNTAIN_NOT_FOUND(HttpStatus.NOT_FOUND, "존재하지 않는 유저 등산 정보입니다."), ALREADY_USERMOUNTAIN_ON_DATE(HttpStatus.CONFLICT, "이미 같은 날에 이 산에 대한 인증이 존재합니다."); private final HttpStatus status; private final String message; ExceptionCode(HttpStatus status, String message) { this.status = status; this.message = message; } }
GlobalExceptionHandler 클래스에 사용된 @ControllerAdvice 어노테이션은 이 클래스가 애플리케이션의 전역 예외 핸들러 역할을 수행하도록 지정한다.
ServiceLogicException은 사용자 정의 예외로, 비즈니스 로직에서 특정 조건을 만족하지 않을 때 발생시킬 수 있고 이 예외에는 ExceptionCode 열거형을 사용하여, 예외의 유형과 HTTP 상태 코드, 사용자에게 보여줄 메시지를 담고 있다. handleServiceLogicException 메서드는 ServiceLogicException이 발생할 때 호출되며, 예외에 담긴 정보를 바탕으로 사용자에게 상태 코드와 메시지를 담은 ErrorResponse를 반환한다.
ErrorResponse 내부 클래스는 클라이언트에 반환할 오류 응답을 위한 데이터 구조이다.
입력 검증 실패시 발생하는 MethodArgumentNotValidException을 처리하기 위한 메서드도 정의되어 있어 이 메서드는 컨트롤러에서 @Valid 어노테이션을 사용한 객체 검증이 실패했을 때 발생하는 예외를 처리한다.
ServiceLogicException 클래스와 ExceptionCode 열거형을 사용해 예외 상황을 구분해 주었다.
728x90'엘리스트랙' 카테고리의 다른 글
최종 프로젝트 개발5 (0) 2024.05.05 최종 프로젝트 개발4 (0) 2024.05.05 최종 프로젝트 개발2 (1) 2024.04.28 최종 프로젝트 개발1 (0) 2024.04.28 최종 프로젝트 api 문서 작성! (0) 2024.04.21