forked from Loopers-dev-lab/loop-pack-be-l2-vol2-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiControllerAdvice.java
More file actions
126 lines (107 loc) · 6.1 KB
/
ApiControllerAdvice.java
File metadata and controls
126 lines (107 loc) · 6.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package com.loopers.interfaces.api;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.loopers.support.error.CoreException;
import com.loopers.support.error.ErrorType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.servlet.resource.NoResourceFoundException;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@RestControllerAdvice
@Slf4j
public class ApiControllerAdvice {
@ExceptionHandler
public ResponseEntity<ApiResponse<?>> handle(CoreException e) {
log.warn("CoreException : {}", e.getCustomMessage() != null ? e.getCustomMessage() : e.getMessage(), e);
return failureResponse(e.getErrorType(), e.getCustomMessage());
}
@ExceptionHandler
public ResponseEntity<ApiResponse<?>> handleBadRequest(MethodArgumentTypeMismatchException e) {
String name = e.getName();
String type = e.getRequiredType() != null ? e.getRequiredType().getSimpleName() : "unknown";
String value = e.getValue() != null ? e.getValue().toString() : "null";
String message = String.format("요청 파라미터 '%s' (타입: %s)의 값 '%s'이(가) 잘못되었습니다.", name, type, value);
return failureResponse(ErrorType.BAD_REQUEST, message);
}
@ExceptionHandler
public ResponseEntity<ApiResponse<?>> handleBadRequest(MissingServletRequestParameterException e) {
String name = e.getParameterName();
String type = e.getParameterType();
String message = String.format("필수 요청 파라미터 '%s' (타입: %s)가 누락되었습니다.", name, type);
return failureResponse(ErrorType.BAD_REQUEST, message);
}
@ExceptionHandler
public ResponseEntity<ApiResponse<?>> handleBadRequest(HttpMessageNotReadableException e) {
String errorMessage;
Throwable rootCause = e.getRootCause();
if (rootCause instanceof InvalidFormatException invalidFormat) {
String fieldName = invalidFormat.getPath().stream()
.map(ref -> ref.getFieldName() != null ? ref.getFieldName() : "?")
.collect(Collectors.joining("."));
String valueIndicationMessage = "";
if (invalidFormat.getTargetType().isEnum()) {
Class<?> enumClass = invalidFormat.getTargetType();
String enumValues = Arrays.stream(enumClass.getEnumConstants())
.map(Object::toString)
.collect(Collectors.joining(", "));
valueIndicationMessage = "사용 가능한 값 : [" + enumValues + "]";
}
String expectedType = invalidFormat.getTargetType().getSimpleName();
Object value = invalidFormat.getValue();
errorMessage = String.format("필드 '%s'의 값 '%s'이(가) 예상 타입(%s)과 일치하지 않습니다. %s",
fieldName, value, expectedType, valueIndicationMessage);
} else if (rootCause instanceof MismatchedInputException mismatchedInput) {
String fieldPath = mismatchedInput.getPath().stream()
.map(ref -> ref.getFieldName() != null ? ref.getFieldName() : "?")
.collect(Collectors.joining("."));
errorMessage = String.format("필수 필드 '%s'이(가) 누락되었습니다.", fieldPath);
} else if (rootCause instanceof JsonMappingException jsonMapping) {
String fieldPath = jsonMapping.getPath().stream()
.map(ref -> ref.getFieldName() != null ? ref.getFieldName() : "?")
.collect(Collectors.joining("."));
errorMessage = String.format("필드 '%s'에서 JSON 매핑 오류가 발생했습니다: %s",
fieldPath, jsonMapping.getOriginalMessage());
} else {
errorMessage = "요청 본문을 처리하는 중 오류가 발생했습니다. JSON 메세지 규격을 확인해주세요.";
}
return failureResponse(ErrorType.BAD_REQUEST, errorMessage);
}
@ExceptionHandler
public ResponseEntity<ApiResponse<?>> handleBadRequest(ServerWebInputException e) {
String missingParams = extractMissingParameter(e.getReason() != null ? e.getReason() : "");
if (!missingParams.isEmpty()) {
String message = String.format("필수 요청 값 '%s'가 누락되었습니다.", missingParams);
return failureResponse(ErrorType.BAD_REQUEST, message);
} else {
return failureResponse(ErrorType.BAD_REQUEST, null);
}
}
@ExceptionHandler
public ResponseEntity<ApiResponse<?>> handleNotFound(NoResourceFoundException e) {
return failureResponse(ErrorType.NOT_FOUND, null);
}
@ExceptionHandler
public ResponseEntity<ApiResponse<?>> handle(Throwable e) {
log.error("Exception : {}", e.getMessage(), e);
return failureResponse(ErrorType.INTERNAL_ERROR, null);
}
private String extractMissingParameter(String message) {
Pattern pattern = Pattern.compile("'(.+?)'");
Matcher matcher = pattern.matcher(message);
return matcher.find() ? matcher.group(1) : "";
}
private ResponseEntity<ApiResponse<?>> failureResponse(ErrorType errorType, String errorMessage) {
return ResponseEntity.status(errorType.getStatus())
.body(ApiResponse.fail(errorType.getCode(), errorMessage != null ? errorMessage : errorType.getMessage()));
}
}