-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[feat] : 에러 처리를 추가하며, 메세지를 정제하여 전달한다 #24
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
39415a8
#23 [feat] : 에러 메세지를 커스텀 할 수 있는 응답 메서드를 추가한다
bbbang105 2be759c
#23 [fix] : MacOS Silicon에서의 라이브러리 누락 문제를 해결한다
bbbang105 67fc44f
#23 [feat] : 쿼리 파라미터 검증 기능을 추가한다
bbbang105 3b2a6bc
#23 [feat] : 유효성 검증 에러를 처리할 수 있다
bbbang105 4f74584
#23 [feat] : 에러 처리를 추가하며, 메세지를 정제하여 전달한다
bbbang105 0c64819
Merge branch 'develop' into feature/#23/handle-valid-error
bbbang105 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
111 changes: 102 additions & 9 deletions
111
src/main/java/kusitms/backend/global/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,41 +1,134 @@ | ||
package kusitms.backend.global.exception; | ||
|
||
import jakarta.validation.ConstraintViolationException; | ||
import kusitms.backend.global.dto.ApiResponse; | ||
import kusitms.backend.global.dto.ErrorReasonDto; | ||
import kusitms.backend.global.status.ErrorStatus; | ||
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 java.util.List; | ||
import java.util.stream.Collectors; | ||
|
||
@Slf4j | ||
@RestControllerAdvice | ||
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { | ||
|
||
// 커스텀 예외 처리 | ||
@ExceptionHandler(CustomException.class) | ||
public ResponseEntity<ApiResponse<ErrorReasonDto>> handleCustomException(CustomException e) { | ||
log.error("CustomException occurred: {}", e.getMessage()); | ||
logError(e.getMessage(), e); | ||
return ApiResponse.onFailure(e.getErrorCode()); | ||
} | ||
|
||
// Security 인증 관련 처리 | ||
@ExceptionHandler(SecurityException.class) | ||
public ResponseEntity<ApiResponse<ErrorReasonDto>> handleSecurityException(SecurityException e) { | ||
log.error("SecurityException: {}", e.getMessage()); | ||
logError(e.getMessage(), e); | ||
return ApiResponse.onFailure(ErrorStatus._UNAUTHORIZED); | ||
} | ||
|
||
// 기타 Exception 처리 | ||
// IllegalArgumentException 처리 (잘못된 인자가 전달된 경우) | ||
@ExceptionHandler(IllegalArgumentException.class) | ||
public ResponseEntity<Object> handleIllegalArgumentException(IllegalArgumentException e) { | ||
String errorMessage = "잘못된 요청입니다: " + e.getMessage(); | ||
logError("IllegalArgumentException", errorMessage); | ||
return ApiResponse.onFailure(ErrorStatus._BAD_REQUEST, errorMessage); | ||
} | ||
|
||
// ConstraintViolationException 처리 (쿼리 파라미터에 올바른 값이 들어오지 않은 경우) | ||
@ExceptionHandler(ConstraintViolationException.class) | ||
public ResponseEntity<Object> handleValidationParameterError(ConstraintViolationException ex) { | ||
String errorMessage = ex.getMessage(); | ||
logError("ConstraintViolationException", errorMessage); | ||
return ApiResponse.onFailure(ErrorStatus._BAD_REQUEST, errorMessage); | ||
} | ||
|
||
// 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); | ||
} | ||
|
||
// 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); | ||
} | ||
|
||
// 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); | ||
} | ||
|
||
// 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); | ||
} | ||
|
||
// 내부 서버 에러 처리 (500) | ||
@ExceptionHandler(Exception.class) | ||
public ResponseEntity<ApiResponse<ErrorReasonDto>> handleException(Exception e) { | ||
log.error("Exception: {}", e.getMessage()); | ||
|
||
if (e instanceof IllegalArgumentException) { | ||
return ApiResponse.onFailure(ErrorStatus._BAD_REQUEST); | ||
} | ||
// 그 외 내부 서버 오류로 처리 | ||
// 서버 내부 에러 발생 시 로그에 예외 내용 기록 | ||
logError(e.getMessage(), e); | ||
return ApiResponse.onFailure(ErrorStatus._INTERNAL_SERVER_ERROR); | ||
} | ||
|
||
// 유효성 검증 오류 메시지 추출 메서드 (FieldErrors) | ||
private String extractFieldErrors(List<FieldError> fieldErrors) { | ||
return fieldErrors.stream() | ||
.map(DefaultMessageSourceResolvable::getDefaultMessage) | ||
.collect(Collectors.joining(", ")); | ||
} | ||
|
||
// 로그 기록 메서드 | ||
private void logError(String message, Object errorDetails) { | ||
log.error("{}: {}", message, errorDetails); | ||
} | ||
} |
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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이거 필수 파라미터 여러개 값이 없으면 여러개 다에 대해서 에러메시지 난오는 거죠???
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이거는 파라미터 1개마다 각각 에러가 발생해서 1개만 처리가 되더라구요 ㅠ
가능하면 다음에 여러개를 동시에 처리할 수 있는 방법을 찾아봐도 좋을 것 같네요!