-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
119 additions
and
67 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
154 changes: 100 additions & 54 deletions
154
src/main/java/side/onetime/exception/GlobalExceptionHandler.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,88 +1,134 @@ | ||
package side.onetime.exception; | ||
|
||
import jakarta.validation.ConstraintViolationException; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.context.support.DefaultMessageSourceResolvable; | ||
import org.springframework.http.HttpHeaders; | ||
import org.springframework.http.HttpStatusCode; | ||
import org.springframework.http.ResponseEntity; | ||
import org.springframework.validation.FieldError; | ||
import org.springframework.web.HttpMediaTypeNotSupportedException; | ||
import org.springframework.web.HttpRequestMethodNotSupportedException; | ||
import org.springframework.web.bind.MethodArgumentNotValidException; | ||
import org.springframework.web.bind.MissingServletRequestParameterException; | ||
import org.springframework.web.bind.annotation.ExceptionHandler; | ||
import org.springframework.web.bind.annotation.RestControllerAdvice; | ||
import org.springframework.web.context.request.WebRequest; | ||
import org.springframework.web.servlet.NoHandlerFoundException; | ||
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; | ||
import side.onetime.global.common.ApiResponse; | ||
import side.onetime.global.common.code.BaseErrorCode; | ||
import side.onetime.global.common.status.ErrorStatus; | ||
import side.onetime.global.common.dto.ErrorReasonDto; | ||
import side.onetime.global.common.status.ErrorStatus; | ||
|
||
import java.util.List; | ||
import java.util.stream.Collectors; | ||
|
||
@RestControllerAdvice | ||
@Slf4j | ||
@RestControllerAdvice | ||
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { | ||
|
||
// Event | ||
@ExceptionHandler(EventException.class) | ||
public ResponseEntity<ApiResponse<BaseErrorCode>> handleTokenException(EventException e) { | ||
EventErrorResult errorResult = e.getEventErrorResult(); | ||
return ApiResponse.onFailure(errorResult); | ||
// 커스텀 예외 처리 | ||
@ExceptionHandler(CustomException.class) | ||
public ResponseEntity<ApiResponse<ErrorReasonDto>> handleCustomException(CustomException e) { | ||
logError(e.getMessage(), e); | ||
return ApiResponse.onFailure(e.getErrorCode()); | ||
} | ||
|
||
// Member | ||
@ExceptionHandler(MemberException.class) | ||
public ResponseEntity<ApiResponse<BaseErrorCode>> handleMemberException(MemberException e) { | ||
MemberErrorResult errorResult = e.getMemberErrorResult(); | ||
return ApiResponse.onFailure(errorResult); | ||
// Security 인증 관련 처리 | ||
@ExceptionHandler(SecurityException.class) | ||
public ResponseEntity<ApiResponse<ErrorReasonDto>> handleSecurityException(SecurityException e) { | ||
logError(e.getMessage(), e); | ||
return ApiResponse.onFailure(ErrorStatus._UNAUTHORIZED); | ||
} | ||
|
||
// Schedule | ||
@ExceptionHandler(ScheduleException.class) | ||
public ResponseEntity<ApiResponse<BaseErrorCode>> handleScheduleException(ScheduleException e) { | ||
ScheduleErrorResult errorResult = e.getScheduleErrorResult(); | ||
return ApiResponse.onFailure(errorResult); | ||
// IllegalArgumentException 처리 (잘못된 인자가 전달된 경우) | ||
@ExceptionHandler(IllegalArgumentException.class) | ||
public ResponseEntity<Object> handleIllegalArgumentException(IllegalArgumentException e) { | ||
String errorMessage = "잘못된 요청입니다: " + e.getMessage(); | ||
logError("IllegalArgumentException", errorMessage); | ||
return ApiResponse.onFailure(ErrorStatus._BAD_REQUEST, errorMessage); | ||
} | ||
|
||
// Selection | ||
@ExceptionHandler(SelectionException.class) | ||
public ResponseEntity<ApiResponse<BaseErrorCode>> handleSelectionException(SelectionException e) { | ||
SelectionErrorResult errorResult = e.getSelectionErrorResult(); | ||
return ApiResponse.onFailure(errorResult); | ||
// ConstraintViolationException 처리 (쿼리 파라미터에 올바른 값이 들어오지 않은 경우) | ||
@ExceptionHandler(ConstraintViolationException.class) | ||
public ResponseEntity<Object> handleValidationParameterError(ConstraintViolationException ex) { | ||
String errorMessage = ex.getMessage(); | ||
logError("ConstraintViolationException", errorMessage); | ||
return ApiResponse.onFailure(ErrorStatus._BAD_REQUEST, errorMessage); | ||
} | ||
|
||
// User | ||
@ExceptionHandler(UserException.class) | ||
public ResponseEntity<ApiResponse<BaseErrorCode>> handleUserException(UserException e) { | ||
UserErrorResult errorResult = e.getUserErrorResult(); | ||
return ApiResponse.onFailure(errorResult); | ||
// MissingServletRequestParameterException 처리 (필수 쿼리 파라미터가 입력되지 않은 경우) | ||
@Override | ||
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, | ||
HttpHeaders headers, | ||
HttpStatusCode status, | ||
WebRequest request) { | ||
String errorMessage = "필수 파라미터 '" + ex.getParameterName() + "'가 없습니다."; | ||
logError("MissingServletRequestParameterException", errorMessage); | ||
return ApiResponse.onFailure(ErrorStatus._BAD_REQUEST, errorMessage); | ||
} | ||
|
||
// Token | ||
@ExceptionHandler(TokenException.class) | ||
public ResponseEntity<ApiResponse<BaseErrorCode>> handleTokenException(TokenException e) { | ||
TokenErrorResult errorResult = e.getTokenErrorResult(); | ||
return ApiResponse.onFailure(errorResult); | ||
// MethodArgumentNotValidException 처리 (RequestBody로 들어온 필드들의 유효성 검증에 실패한 경우) | ||
@Override | ||
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, | ||
HttpHeaders headers, | ||
HttpStatusCode status, | ||
WebRequest request) { | ||
String combinedErrors = extractFieldErrors(ex.getBindingResult().getFieldErrors()); | ||
logError("Validation error", combinedErrors); | ||
return ApiResponse.onFailure(ErrorStatus._BAD_REQUEST, combinedErrors); | ||
} | ||
|
||
// EventParticipation | ||
@ExceptionHandler(EventParticipationException.class) | ||
public ResponseEntity<ApiResponse<BaseErrorCode>> handleEventParticipationException(EventParticipationException e) { | ||
EventParticipationErrorResult errorResult = e.getEventParticipationErrorResult(); | ||
return ApiResponse.onFailure(errorResult); | ||
// NoHandlerFoundException 처리 (요청 경로에 매핑된 핸들러가 없는 경우) | ||
@Override | ||
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, | ||
HttpHeaders headers, | ||
HttpStatusCode status, | ||
WebRequest request) { | ||
String errorMessage = "해당 경로에 대한 핸들러를 찾을 수 없습니다: " + ex.getRequestURL(); | ||
logError("NoHandlerFoundException", errorMessage); | ||
return ApiResponse.onFailure(ErrorStatus._NOT_FOUND_HANDLER, errorMessage); | ||
} | ||
|
||
// AccessDeniedException 등 보안 관련 에러 처리 | ||
@ExceptionHandler(SecurityException.class) | ||
public ResponseEntity<ErrorReasonDto> handleSecurityException(SecurityException e) { | ||
log.error("SecurityException: {}", e.getMessage()); | ||
return ResponseEntity.status(ErrorStatus._UNAUTHORIZED.getHttpStatus()) | ||
.body(ErrorStatus._UNAUTHORIZED.getReasonHttpStatus()); | ||
// HttpRequestMethodNotSupportedException 처리 (지원하지 않는 HTTP 메소드 요청이 들어온 경우) | ||
@Override | ||
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, | ||
HttpHeaders headers, | ||
HttpStatusCode status, | ||
WebRequest request) { | ||
String errorMessage = "지원하지 않는 HTTP 메소드 요청입니다: " + ex.getMethod(); | ||
logError("HttpRequestMethodNotSupportedException", errorMessage); | ||
return ApiResponse.onFailure(ErrorStatus._METHOD_NOT_ALLOWED, errorMessage); | ||
} | ||
|
||
// HttpMediaTypeNotSupportedException 처리 (지원하지 않는 미디어 타입 요청이 들어온 경우) | ||
@Override | ||
protected ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, | ||
HttpHeaders headers, | ||
HttpStatusCode status, | ||
WebRequest request) { | ||
String errorMessage = "지원하지 않는 미디어 타입입니다: " + ex.getContentType(); | ||
logError("HttpMediaTypeNotSupportedException", errorMessage); | ||
return ApiResponse.onFailure(ErrorStatus._UNSUPPORTED_MEDIA_TYPE, errorMessage); | ||
} | ||
|
||
// 기타 Exception 처리 | ||
// 내부 서버 에러 처리 (500) | ||
@ExceptionHandler(Exception.class) | ||
public ResponseEntity<ErrorReasonDto> handleException(Exception e) { | ||
log.error("Exception: {}", e.getMessage()); | ||
public ResponseEntity<ApiResponse<ErrorReasonDto>> handleException(Exception e) { | ||
// 서버 내부 에러 발생 시 로그에 예외 내용 기록 | ||
logError(e.getMessage(), e); | ||
return ApiResponse.onFailure(ErrorStatus._INTERNAL_SERVER_ERROR); | ||
} | ||
|
||
if (e instanceof IllegalArgumentException) { | ||
return ResponseEntity.status(ErrorStatus._BAD_REQUEST.getHttpStatus()) | ||
.body(ErrorStatus._BAD_REQUEST.getReasonHttpStatus()); | ||
} | ||
// 유효성 검증 오류 메시지 추출 메서드 (FieldErrors) | ||
private String extractFieldErrors(List<FieldError> fieldErrors) { | ||
return fieldErrors.stream() | ||
.map(DefaultMessageSourceResolvable::getDefaultMessage) | ||
.collect(Collectors.joining(", ")); | ||
} | ||
|
||
// 그 외 내부 서버 오류로 처리 | ||
return ResponseEntity.status(ErrorStatus._INTERNAL_SERVER_ERROR.getHttpStatus()) | ||
.body(ErrorStatus._INTERNAL_SERVER_ERROR.getReasonHttpStatus()); | ||
// 로그 기록 메서드 | ||
private void logError(String message, Object errorDetails) { | ||
log.error("{}: {}", message, errorDetails); | ||
} | ||
} |