-
Notifications
You must be signed in to change notification settings - Fork 1
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] 전역적 예외 및 핸들러 추가 #4
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4036e91
feat: 전역적 예외 및 핸들러 추가
helenason 91906dc
refactor: 500 서버 에러 코드 추가
helenason 315930c
feat: 에러 응답에 code 필드를 포함하도록 변경
helenason b881409
feat: ErrorResponse 필드 보완 및 유효성 검사 실패 에러 응답 추가
helenason 820af71
feat: 공통 성공 응답 클래스 정의
helenason 5814a13
refactor: 예외 및 성공 응답 반환 공통 로직 추출
helenason 575c869
feat: 서버 에러 응답 구체화
helenason 4e51c4c
feat: 성공 응답시 다양한 status 응답할 수 있도록 변경
helenason 4fcc3eb
feat: 유효성 예외 발생 시 상태코드 400 반환
helenason 5c5898f
feat: 유효하지 않은 API 경로 예외 핸들러 추가
helenason 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
11 changes: 11 additions & 0 deletions
11
src/main/java/com/evenly/blok/global/exception/BlokException.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 |
---|---|---|
@@ -0,0 +1,11 @@ | ||
package com.evenly.blok.global.exception; | ||
|
||
import lombok.AllArgsConstructor; | ||
import lombok.Getter; | ||
|
||
@Getter | ||
@AllArgsConstructor | ||
public class BlokException extends RuntimeException { // TODO: 서비스명에 맞게 변경 | ||
|
||
private final ErrorCode errorCode; | ||
} |
18 changes: 18 additions & 0 deletions
18
src/main/java/com/evenly/blok/global/exception/CommonErrorCode.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 |
---|---|---|
@@ -0,0 +1,18 @@ | ||
package com.evenly.blok.global.exception; | ||
|
||
import lombok.Getter; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.http.HttpStatus; | ||
|
||
@Getter | ||
@RequiredArgsConstructor | ||
public enum CommonErrorCode implements ErrorCode { | ||
|
||
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "서버 관리자에게 문의하세요."), | ||
INVALID_REQUEST_VALUE(HttpStatus.BAD_REQUEST, "유효하지 않은 요청값입니다."), | ||
INVALID_REQUEST_URL(HttpStatus.BAD_REQUEST, "유효하지 않은 경로입니다."), | ||
; | ||
|
||
private final HttpStatus status; | ||
private final String message; | ||
} |
10 changes: 10 additions & 0 deletions
10
src/main/java/com/evenly/blok/global/exception/ErrorCode.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 |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package com.evenly.blok.global.exception; | ||
|
||
import org.springframework.http.HttpStatus; | ||
|
||
public interface ErrorCode { | ||
|
||
HttpStatus getStatus(); | ||
|
||
String getMessage(); | ||
} |
39 changes: 39 additions & 0 deletions
39
src/main/java/com/evenly/blok/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 |
---|---|---|
@@ -0,0 +1,39 @@ | ||
package com.evenly.blok.global.exception; | ||
|
||
import com.evenly.blok.global.exception.dto.ErrorResponse; | ||
import com.evenly.blok.global.exception.dto.ServerErrorResponse; | ||
import com.evenly.blok.global.exception.dto.ValidationErrorResponse; | ||
import org.springframework.web.bind.MethodArgumentNotValidException; | ||
import org.springframework.web.bind.annotation.ExceptionHandler; | ||
import org.springframework.web.bind.annotation.RestControllerAdvice; | ||
import org.springframework.web.servlet.resource.NoResourceFoundException; | ||
|
||
@RestControllerAdvice | ||
public class GlobalExceptionHandler { | ||
|
||
@ExceptionHandler | ||
public ErrorResponse handle(BlokException ex) { | ||
ErrorCode errorCode = ex.getErrorCode(); | ||
return ErrorResponse.of(errorCode); | ||
} | ||
|
||
@ExceptionHandler | ||
public ErrorResponse handle(NoResourceFoundException ex) { | ||
ErrorCode errorCode = CommonErrorCode.INVALID_REQUEST_URL; | ||
return ErrorResponse.of(errorCode); | ||
} | ||
|
||
@ExceptionHandler | ||
public ErrorResponse handle(MethodArgumentNotValidException ex) { | ||
ErrorCode errorCode = CommonErrorCode.INVALID_REQUEST_VALUE; | ||
return ValidationErrorResponse.of(errorCode, ex); | ||
} | ||
|
||
@ExceptionHandler | ||
public ErrorResponse handle(Exception ex) { | ||
// TODO: 로그 추가 | ||
ex.printStackTrace(); | ||
ErrorCode errorCode = CommonErrorCode.INTERNAL_SERVER_ERROR; | ||
return ServerErrorResponse.of(errorCode, ex); | ||
} | ||
} |
24 changes: 24 additions & 0 deletions
24
src/main/java/com/evenly/blok/global/exception/dto/ErrorResponse.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 |
---|---|---|
@@ -0,0 +1,24 @@ | ||
package com.evenly.blok.global.exception.dto; | ||
|
||
import com.evenly.blok.global.exception.ErrorCode; | ||
import java.time.LocalDateTime; | ||
import lombok.Getter; | ||
import org.springframework.http.HttpStatus; | ||
|
||
@Getter | ||
public class ErrorResponse { | ||
|
||
private final HttpStatus status; | ||
private final String message; | ||
private final LocalDateTime timestamp; | ||
|
||
protected ErrorResponse(ErrorCode errorCode) { | ||
this.status = errorCode.getStatus(); | ||
this.message = errorCode.getMessage(); | ||
this.timestamp = LocalDateTime.now(); | ||
} | ||
|
||
public static ErrorResponse of(ErrorCode errorCode) { | ||
return new ErrorResponse(errorCode); | ||
} | ||
} |
29 changes: 29 additions & 0 deletions
29
src/main/java/com/evenly/blok/global/exception/dto/ServerErrorResponse.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 |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package com.evenly.blok.global.exception.dto; | ||
|
||
import com.evenly.blok.global.exception.ErrorCode; | ||
import lombok.Getter; | ||
|
||
@Getter | ||
public class ServerErrorResponse extends ErrorResponse { | ||
|
||
private final ErrorDetail error; | ||
|
||
private ServerErrorResponse(ErrorCode errorCode, ErrorDetail error) { | ||
super(errorCode); | ||
this.error = error; | ||
} | ||
|
||
public static ServerErrorResponse of(ErrorCode errorCode, Exception ex) { | ||
ErrorDetail errorDetail = new ErrorDetail(ex); | ||
return new ServerErrorResponse(errorCode, errorDetail); | ||
} | ||
|
||
private record ErrorDetail(String exception, | ||
String message, | ||
String stackTrace) { | ||
|
||
private ErrorDetail(Exception ex) { | ||
this(ex.getClass().getSimpleName(), ex.getMessage(), ex.getStackTrace()[0].getClassName()); | ||
} | ||
} | ||
} |
35 changes: 35 additions & 0 deletions
35
src/main/java/com/evenly/blok/global/exception/dto/ValidationErrorResponse.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 |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package com.evenly.blok.global.exception.dto; | ||
|
||
import com.evenly.blok.global.exception.ErrorCode; | ||
import java.util.List; | ||
import lombok.Getter; | ||
import org.springframework.validation.FieldError; | ||
import org.springframework.web.bind.MethodArgumentNotValidException; | ||
|
||
@Getter | ||
public class ValidationErrorResponse extends ErrorResponse { | ||
|
||
private final List<FieldErrorDetail> errors; | ||
|
||
private ValidationErrorResponse(ErrorCode errorCode, List<FieldErrorDetail> errors) { | ||
super(errorCode); | ||
this.errors = errors; | ||
} | ||
|
||
public static ValidationErrorResponse of(ErrorCode errorCode, MethodArgumentNotValidException ex) { | ||
List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors(); | ||
List<FieldErrorDetail> fieldErrorDetails = fieldErrors.stream() | ||
.map(FieldErrorDetail::new) | ||
.toList(); | ||
return new ValidationErrorResponse(errorCode, fieldErrorDetails); | ||
} | ||
|
||
private record FieldErrorDetail(String field, | ||
String message, | ||
Object value) { | ||
|
||
private FieldErrorDetail(FieldError fieldError) { | ||
this(fieldError.getField(), fieldError.getDefaultMessage(), fieldError.getRejectedValue()); | ||
} | ||
} | ||
} |
37 changes: 37 additions & 0 deletions
37
src/main/java/com/evenly/blok/global/response/GlobalResponseHandler.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 |
---|---|---|
@@ -0,0 +1,37 @@ | ||
package com.evenly.blok.global.response; | ||
|
||
import com.evenly.blok.global.exception.dto.ErrorResponse; | ||
import org.springframework.core.MethodParameter; | ||
import org.springframework.http.MediaType; | ||
import org.springframework.http.converter.HttpMessageConverter; | ||
import org.springframework.http.server.ServerHttpRequest; | ||
import org.springframework.http.server.ServerHttpResponse; | ||
import org.springframework.web.bind.annotation.RestControllerAdvice; | ||
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; | ||
|
||
@RestControllerAdvice | ||
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> { | ||
|
||
@Override | ||
public boolean supports(MethodParameter returnType, | ||
Class<? extends HttpMessageConverter<?>> converterType) { | ||
return true; | ||
} | ||
|
||
@Override | ||
public Object beforeBodyWrite(Object body, | ||
MethodParameter returnType, | ||
MediaType selectedContentType, | ||
Class<? extends HttpMessageConverter<?>> selectedConverterType, | ||
ServerHttpRequest request, | ||
ServerHttpResponse response) { | ||
|
||
if (body instanceof ErrorResponse errorResponse) { | ||
response.setStatusCode(errorResponse.getStatus()); | ||
} | ||
if (body instanceof SuccessResponse successResponse) { | ||
response.setStatusCode(successResponse.getStatus()); | ||
} | ||
return body; | ||
} | ||
} |
28 changes: 28 additions & 0 deletions
28
src/main/java/com/evenly/blok/global/response/SuccessResponse.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 |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package com.evenly.blok.global.response; | ||
|
||
import java.time.LocalDateTime; | ||
import lombok.AccessLevel; | ||
import lombok.Getter; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.http.HttpStatus; | ||
|
||
@Getter | ||
@RequiredArgsConstructor(access = AccessLevel.PRIVATE) | ||
public class SuccessResponse { | ||
|
||
private static final HttpStatus DEFAULT_HTTP_STATUS = HttpStatus.OK; | ||
private static final String DEFAULT_MESSAGE = "요청이 성공적으로 처리되었습니다."; | ||
|
||
private final HttpStatus status; | ||
private final String message; | ||
private final LocalDateTime timestamp; | ||
private final Object data; | ||
|
||
public static SuccessResponse of(Object data) { | ||
return new SuccessResponse(DEFAULT_HTTP_STATUS, DEFAULT_MESSAGE, LocalDateTime.now(), data); | ||
} | ||
|
||
public static SuccessResponse of(HttpStatus status, Object data) { | ||
return new SuccessResponse(status, DEFAULT_MESSAGE, LocalDateTime.now(), data); | ||
} | ||
} |
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.
저는 전 프로젝트에서 @ExceptionHandler(EntityNotFoundException.class) 이런식으로 각 Exception에 대한 예외 Handling을 따로 적용했던거 같은데 어떻게 생각하시는지 궁금합니다!
또한, 중요한 예외의 경우 log도 추가했었는데 저희 컨벤션에 warn 부터는 logging이 되어야한다는 부분이 있어서 이 부분도 고려해봐주시면 좋을거 같아요!
그래서 같은 맥락으로 exception의 이름도 추가하고, timestamp도 추가하면 나중에 logging 시 좋을거 같아서 의견 남겨요!
아래는 제가 생각하는 예시입니다.!!
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. @ExceptionHandler 파라미터 선언 관련
@ExceptionHandler
의 파라미터가 존재하지 않아도 선언한 메서드의 파라미터를 통해 예외 타입을 지정할 수 있는데요! (스프링에서도 메서드 시그니처 파라미터를 통해서만 예외 타입을 지정하여 실수를 방지할 것을 추천하기도 합니다) 저도 마찬가지로 중복 코드를 선호하지 않아서, 파라미터만으로 예외 타입을 선언하도록 하였습니다 :) 이 내용을 기반으로 다시 한번 경호님의 의견을 여쭙습니다!2. 로그 기준 및 로그에 담을 정보 관련
로그의 경우 컨벤션을 추후 확정하는 것으로 알고 있었어서 기존에는 추가하지 않았었는데요, 로그 관련하여서도 다양한 이야기를 해볼 수 있을 것 같아요! (추후 회의를 통해 명확한 기준을 정하는 것도 좋을 것 같습니다)
3. 에러 응답 관련
저는 고민 끝에 아래와 같은 형태로 모든 비즈니스 예외에 대해 BlokException(커스텀 예외)를 반환하도록 하였는데요.
경호님이 위에서 제시해주신 예시를 기반으로 저의 의견을 소개드리고 싶어요!
제가 고민했던 부분들을 경호님이 쏙쏙 짚어주셔서 적다보니 내용이 길어졌는데요 하하 (다음엔 PR description에 고민한 내용을 최대한 적어보겠습니닷..)
불필요한 중복을 최대한 쳐내기 위해 고민 끝에 내린 결론은, 예외를 반환할 때 헤더에 status를 포함하고, 바디에 에러메시지를 포함하자는 결론이었습니다. 하지만 반대로 중복된 정보는 오히려 정보를 얻기 수월하다는 장점이 있을 수 있겠어요. 따라서 애플리케이션 단에서 예외를 발생시킬 방법과, 클라이언트에게 전달할 예외 응답과 관련하여 저희 셋이 논의할 필요가 있어 보여요. 그에 따라 response의 형태도 달라질 것 같아요. 여러분들의 전반적인 의견이 궁금합니다!
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.
너무나 친절한 설명 감사드립니다!!
ExceptionHandler, log timestamp, status 모두 결국엔 중복에 대한 고민 결과라고 생각이 들어서 함께 의견 남겨요!
결론적으로는 채영님 의견을 들어보니 충분히 공감되는 부분이라서 그대로 진행해도 좋을거 같다고 생각했어요!
제가 저 exception을 명시하거나 timestamp, status를 과거에 왜 찍었는지 생각했을 때도 결국엔 좀더 관리 측면에서 직관적이라 편하다는 니즈가 있었던거 같아요.
그래서 이 부분은 저희가 진행하다가 필요하면 다시 고민해볼 문제가 맞고 지금은 불필요한 부분 같다는게 채영님의 의견을 듣고 난 후의 생각이었습니다!! 너무나 친절한 설명 조와요~~
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.
두분께서 충분한 고민을 거쳐 의견을 정리해주셔서 너무 감사드립니다!!
추후 논의를 위한 고민해볼만한 몇 가지 포인트들 한 번 정리해봤어요.
에러를 로깅하는 과정에서 중복된 데이터를 제거 및 꼭 필요한 데이터만 첨부
Response Status 에만 상태값을 의지
공통 에러 클래스를 완벽하게 통일
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.
오 좋은 의견 정말 감사해요!
응답이 많아지면 복잡도가 높아져 클라이언트 입장에서 오히려 읽기 불편할 것이라 생각했다가, 이전에 경호님 코멘트를 받고 변경에 아주 민감한 API응답은 DB 설계할 때와 같이 최대한 변경되지 않도록 세세한 정보를 담는 방향이 더 적절할 수 있다는 생각을 매일같이 하고 있었는데요 ㅋㅋㅋㅋ 찬기님이 주신 다른 근거들을 접하니 더더욱 그렇게 생각하게 되었습니다!! 특히 아래 부분이 인상적이었어요.
이렇게 세세한 정보를 담도록 한다면 에러 응답뿐 아니라 공통 응답 클래스도 더더욱 필요해지겠네요. 첨부해주신 예시 참고해서 코드 수정해보겠습니다 👊