일정관리 서버 프로젝트가 끝나고 튜터님께 받은 1:1 피드백 중
만약 프로젝트의 규모가 커져서 다양한 상황의 예외가 발생한다면 매번 예외 클래스를 생성하고 핸들러로 처리하는 것이 부담스러워질 것입니다. 이런 상황에서 어떻게 유지보수가 쉽도록 예외 처리를 할 수 있을지 고민해보세요.
이런 내용이 있었다.
exception 종류마다 클래스를 만들고 그걸 한번에 관리하는 핸들러를 통해 예외를 처리했는데 생각해보니 예외 상황이 많아질수록 비효율적이긴 하다.
예외처리 방법
1. BusinessException을 정의한다. 공통 예외를 처리하는 부분.
import org.springframework.http.HttpStatus;
public class BusinessException extends RuntimeException {
private final HttpStatus httpStatus;
public BusinessException(String message, HttpStatus httpStatus) {
super(message);
this.httpStatus = httpStatus;
}
public HttpStatus getHttpStatus() {
return httpStatus;
}
}
2. GlobalExceptionHandler에서 예외처리
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<Map<String, String>> handleBusinessException(BusinessException e) {
Map<String, String> errorResponse = new HashMap<>();
errorResponse.put("message", e.getMessage());
return ResponseEntity.status(e.getHttpStatus()).body(errorResponse);
}
}
튜터님 코드
package com.example.schedule.config;
import com.example.exception.ApplicationException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ApplicationException.class)
public ResponseEntity<Map<String, Object>> handleApplicationException(ApplicationException ex) {
return getErrorResponse(ex.getStatus(), ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> handleValidationException(MethodArgumentNotValidException ex) {
String firstErrorMessage = ex.getBindingResult()
.getFieldErrors()
.stream()
.findFirst()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.orElseThrow(() -> new IllegalStateException("검증 에러가 반드시 존재해야 합니다."));
return getErrorResponse(HttpStatus.BAD_REQUEST, firstErrorMessage);
}
private ResponseEntity<Map<String, Object>> getErrorResponse(HttpStatus status, String message) {
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("status", status.name());
errorResponse.put("code", status.value());
errorResponse.put("message", message);
return new ResponseEntity<>(errorResponse, status);
}
}
사용 예시
throw new BusinessException("삭제할 수 없는 일정입니다.", HttpStatus.FORBIDDEN);
'프로젝트 > 일정관리' 카테고리의 다른 글
ERROR 2059 (HY000): Authentication plugin 'auth_gssapi_client' cannot be loaded (0) | 2025.02.13 |
---|---|
[일정관리앱ver.2] updatedDate(updatedAt) 즉시 반영이 안되는 문제 (0) | 2025.02.12 |
[일정관리앱] Page 객체 사용시 콘솔창 경고 문구 (0) | 2025.02.03 |
[일정관리앱] 프로젝트 lv2까지의 구현 과정 및 구현 방향 (0) | 2025.01.27 |