Skip to content

Commit

Permalink
refactor(GlobalExceptionHandler): HttpMessageNotReadableException 발생 …
Browse files Browse the repository at this point in the history
…시 서버에서 처리한 응답으로 예외 메시지 변경 (#796)
  • Loading branch information
jminkkk authored Oct 15, 2024
1 parent 5e5efe2 commit 9078171
Showing 1 changed file with 22 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.lang.Nullable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
Expand All @@ -16,6 +18,9 @@
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonMappingException.Reference;

import lombok.extern.slf4j.Slf4j;

@Slf4j
Expand Down Expand Up @@ -51,6 +56,23 @@ protected ResponseEntity<Object> handleMethodArgumentNotValid(
.body(codeZapException.toProblemDetail());
}

@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(
HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
String exceptionMessage = "잘못된 JSON 형식입니다.";
if (ex.getCause() instanceof JsonMappingException jsonMappingException) {
exceptionMessage = jsonMappingException.getPath().stream()
.map(Reference::getFieldName)
.collect(Collectors.joining(" ")) + " 필드의 형식이 잘못되었습니다.";
}

CodeZapException codeZapException =
new CodeZapException(ErrorCode.INVALID_REQUEST, String.join("\n", exceptionMessage));

return ResponseEntity.status(codeZapException.getErrorCode().getHttpStatus())
.body(codeZapException.toProblemDetail());
}

@ExceptionHandler
public ResponseEntity<ProblemDetail> handleException(Exception exception) {
log.error("[Exception] 예상치 못한 오류 {} 가 발생했습니다.", exception.getClass().getName(), exception);
Expand Down

0 comments on commit 9078171

Please sign in to comment.