티스토리 뷰

1. ResponseEntity<T>

@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception ex) {
    // 예외 발생 시 500 Internal Server Error와 오류 메시지 반환
    return new ResponseEntity<>("Internal Server Error: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}

2. Optional을 통한 예외처리

- 일반적으로 null에 대해 안전한 처리를 위해 Optional을 이용

public Optional<String> findUserNameById(Long id) {
    User user = userRepository.findById(id);
    
    // 값이 존재하면 name을 반환, 아니면 Optional.empty() 반환
    return Optional.ofNullable(user).map(User::getName);
}
더보기

- 기억이 드문거리는 날 위한 예시들,,

 

1. ifPresent() :: 값이 존재할 때만 특정 작업을 수행하는 메서드

public void sendWelcomeEmail(Long id) {
    Optional.ofNullable(userRepository.findById(id))
        .map(User::getEmail)
        .ifPresent(email -> emailService.sendEmail(email, "Welcome!"));
}

 

2. filter() :: 특정 조건을 만족하는 경우에만 값이 존재하는지 확인 가능

public Optional<String> getUserName(Long id) {
    return Optional.ofNullable(userRepository.findById(id))
        .filter(user -> user.getAge() > 18) // 나이가 18세 이상인 사용자만 필터링
        .map(User::getName);
}

 

- null이라면 예외를 발생시켜 처리 가능

public String getUserName(Long id) {
    return Optional.ofNullable(userRepository.findById(id))
        .map(User::getName)
        .orElseThrow(() -> new UserNotFoundException("User not found with id: " + id));
}

3. BaseResponse

:: 커스텀 코드를 갖는 반환 클래스

:: HTTP 표준 응답 코드로 나열하기에는 무리가 있음 -> 커스텀 사용

:: Enum으로 반환 값과 메세지를 지정하고 반환하는게 제일 깔끔 

:: 성공/실패와 같이 상황에 따른 객체 생성을 위한 정적 팩토리 메서드를 적용하면 좋음..

- Enum 예시

더보기
@Getter
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
public enum ExceptionType {
    USER_NOT_FOUND("A04", "유저가 데이터베이스 내 존재하지 않습니다. 유저 id : ", HttpStatus.NOT_FOUND, Level.WARN),
    PAYMENT_NOT_FOUND("A05", "결제 데이터가 데이터베이스 내 존재하지 않습니다. 결제 id : ", HttpStatus.NOT_FOUND, Level.WARN),
    STATUS_NOT_FOUND("A06", "상태가 데이터베이스 내 존재하지 않습니다. 상태 id : ", HttpStatus.NOT_FOUND, Level.WARN),
    INVALID_INPUT("B01", "값을 제대로 좀 주세요 : ", HttpStatus.BAD_REQUEST, Level.WARN),
    UNCLASSIFIED_ERROR("Z10", "내부에서 에러가 발생했습니다. 추가 메세지 : ", HttpStatus.INTERNAL_SERVER_ERROR, Level.ERROR);

    String type;
    String desc;
    HttpStatus status;
    Level level;
}

 

- 간단한 예시

더보기
@Getter
@Setter
public class BaseResponse<T> {
    private int status;  // 응답 상태 코드
    private String message;  // 응답 메시지
    private T data;  // 응답 데이터 (제네릭 타입으로 다양한 데이터 타입을 처리 가능)

    // 생성자
    public BaseResponse(int status, String message) {
        this.status = status;
        this.message = message;
    }

    public BaseResponse(int status, String message, T data) {
        this.status = status;
        this.message = message;
        this.data = data;
    }

    // 성공 응답 반환 메서드
    public static <T> BaseResponse<T> success(T data) {
        return new BaseResponse<>(200, "Success", data);
    }

    // 실패 응답 반환 메서드
    public static <T> BaseResponse<T> error(int status, String message) {
        return new BaseResponse<>(status, message);
    }
}

 

@GetMapping("/user/{id}")
public BaseResponse<User> getUserById(@PathVariable Long id) {
    User user = userRepository.findById(id).orElse(null);

    if (user == null) {
        return BaseResponse.error(404, "User not found with id: " + id);  // 오류 처리
    }

    return BaseResponse.success(user);  // 성공적인 응답 반환
}

 

@GetMapping("/user/{id}")
public BaseResponse<User> getUserById(@PathVariable Long id) {
    User user = userRepository.findById(id).orElse(null);

    if (user == null) {
        return BaseResponse.error(404, "User not found with id: " + id);  // 오류 처리
    }

    return BaseResponse.success(user);  // 성공적인 응답 반환
}

 

@GetMapping("/order/{orderId}")
public BaseResponse<Order> getOrderStatus(@PathVariable Long orderId) {
    Order order = orderService.findOrderById(orderId);

    if (order == null) {
        return BaseResponse.error(500, "Internal Server Error: Order not found");
    } else if (order.getStatus().equals("CANCELLED")) {
        return BaseResponse.error(400, "Order is cancelled");
    }

    return BaseResponse.success(order);
}

- 적용 예시

더보기
@Getter
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class BaseResponse<T> {
    private final boolean success;
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private final String type;
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private final String message;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private final T body;

    public static <T> BaseResponse<T> of(boolean success, String type, String message, T body) {
        return new BaseResponse<T>(success, type, message, body);
    }
    public static <T> BaseResponse<T> success(T body) {
        return new BaseResponse<T>(true, null, null, body);
    }
    public static <T> BaseResponse<T> failure(ExceptionType type) {
        return new BaseResponse<T>(false, type.getType(), type.getDesc(), null);
    }
}

4. @ControllerAdvice

:: 전역적인 예외처리 담당 어노테이션

:: Controller 의 Exception 처리에 대한 책임을 ControllerAdvice에 위임

:: 중앙 집중식 예외처리를 지원 -> 여러 개의 컨트롤러에서 발생할 수 있는 예외를 하나의 클래스에서 처리 가능

:: @RestControllerAdvice = @ControllerAdvice + @ResponseBody

 

4.1 전역 예외처리 흐름

 

  1. 클라이언트가 요청을 보냄.
  2. 요청을 처리하는 컨트롤러 메서드에서 예외가 발생 시, 해당 예외는 @ControllerAdvice 클래스에서 처리 .
  3. @ControllerAdvice 내에 정의된 @ExceptionHandler 메서드가 실행-> 예외를 처리
  4. 적절한 응답을 클라이언트에게 전달

 

@ControllerAdvice
public class GlobalExceptionHandler {

    // 특정 예외를 처리하는 메서드
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<String> handleNullPointerException(NullPointerException ex) {
        return new ResponseEntity<>("NullPointerException 발생", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 모든 예외를 처리하는 메서드
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        return new ResponseEntity<>("서버 오류 발생", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
더보기

 

  1. @ControllerAdvice로 정의된 클래스는 애플리케이션 내 모든 컨트롤러에서 발생하는 예외를 처리
  2. @ExceptionHandler 애너테이션을 사용하여 특정 예외나 모든 예외를 처리
  3. handleNullPointerException 메서드는 NullPointerException이 발생했을 때 실행
  4. handleException 메서드는 그 외의 모든 예외를 처리

 

-적용 예시

더보기
@Getter
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class BaseResponse<T> {
    private final boolean success;
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private final String type;
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private final String message;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private final T body;

    public static <T> BaseResponse<T> of(boolean success, String type, String message, T body) {
        return new BaseResponse<T>(success, type, message, body);
    }

    public static <T> BaseResponse<T> success(T body) {
        return new BaseResponse<T>(true, null, null, body);
    }

    public static <T> BaseResponse<T> failure(ExceptionType type) {
        return new BaseResponse<T>(false, type.getType(), type.getDesc(), null);
    }
    public static <T> BaseResponse<T> failure(ExceptionType type, T body) {
        return new BaseResponse<T>(false, type.getType(), type.getDesc(), body);
    }
    public static <T> BaseResponse<T> failure(ExceptionType type, String message) {
        return new BaseResponse<T>(false, type.getType(), type.getDesc() + message, null);
    }
}

 

@Slf4j
@ControllerAdvice/* Controller 앞단에서 발생하는 에러를 캐치하기 위함 */
public class CustomExceptionHandler {
    /* @ExceptionHandler 로 어떤 에러인지?를 명시하여 그에 해당하는 에러가 발생 시 바로 아래 정의된 메서드에서 처리를 한다. */
    @ExceptionHandler // @ExceptionHandler(value = {UserNotFoundException.class, NullPointerException.class})
    public BaseResponse<Void> handle(CustomException e) {
        ExceptionType type = e.getType();
        log.atLevel(type.getLevel()).setCause(e).log(e.getMessage());
        return BaseResponse.failure(type);
    }
    @ExceptionHandler // @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<List<FieldErrorDto>> handle(MethodArgumentNotValidException e) {
        List<FieldErrorDto> errors = new ArrayList<>();
        StringBuilder messageBuilder = new StringBuilder();
        for (ObjectError each : e.getBindingResult().getAllErrors()) {
            FieldError eachError = (FieldError) each;
            messageBuilder.append(String.format("[%s = %s : %s] ", eachError.getField(), eachError.getRejectedValue(), eachError.getDefaultMessage()));
            errors.add(new FieldErrorDto(eachError.getField(), eachError.getRejectedValue(), eachError.getDefaultMessage()));
        }
        log.warn(messageBuilder.toString(), e);
        return BaseResponse.failure(ExceptionType.INVALID_INPUT, errors);
    }
    @ExceptionHandler
    public BaseResponse<Void> handle(Exception e) {
        log.error(e.getMessage(), e);
        return BaseResponse.failure(ExceptionType.UNCLASSIFIED_ERROR);
    }
}

 

 

 


참고

 

ASAC 수업자료

 

 

근데 좀 어렵다..

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/03   »
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
글 보관함