forked from kafbat/kafka-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGlobalErrorWebExceptionHandler.java
168 lines (145 loc) · 6.57 KB
/
GlobalErrorWebExceptionHandler.java
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package io.kafbat.ui.exception;
import com.google.common.base.Throwables;
import com.google.common.collect.Sets;
import io.kafbat.ui.config.CorsGlobalConfiguration;
import io.kafbat.ui.model.ErrorResponseDTO;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.Mono;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {
public GlobalErrorWebExceptionHandler(ErrorAttributes errorAttributes,
ApplicationContext applicationContext,
ServerCodecConfigurer codecConfigurer) {
super(errorAttributes, new WebProperties.Resources(), applicationContext);
this.setMessageWriters(codecConfigurer.getWriters());
}
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
private Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
Throwable throwable = getError(request);
// validation and params binding errors
if (throwable instanceof WebExchangeBindException) {
return render((WebExchangeBindException) throwable, request);
}
// requests mapping & access errors
if (throwable instanceof ResponseStatusException) {
return render((ResponseStatusException) throwable, request);
}
// custom exceptions
if (throwable instanceof CustomBaseException) {
return render((CustomBaseException) throwable, request);
}
return renderDefault(throwable, request);
}
private Mono<ServerResponse> renderDefault(Throwable throwable, ServerRequest request) {
var response = new ErrorResponseDTO()
.code(ErrorCode.UNEXPECTED.code())
.message(coalesce(throwable.getMessage(), "Unexpected internal error"))
.requestId(requestId(request))
.timestamp(currentTimestamp())
.stackTrace(Throwables.getStackTraceAsString(throwable));
return ServerResponse
.status(ErrorCode.UNEXPECTED.httpStatus())
.contentType(MediaType.APPLICATION_JSON)
.headers(headers(request))
.bodyValue(response);
}
private Mono<ServerResponse> render(CustomBaseException baseException, ServerRequest request) {
ErrorCode errorCode = baseException.getErrorCode();
var response = new ErrorResponseDTO()
.code(errorCode.code())
.message(coalesce(baseException.getMessage(), "Internal error"))
.requestId(requestId(request))
.timestamp(currentTimestamp())
.stackTrace(Throwables.getStackTraceAsString(baseException));
return ServerResponse
.status(errorCode.httpStatus())
.contentType(MediaType.APPLICATION_JSON)
.headers(headers(request))
.bodyValue(response);
}
private Mono<ServerResponse> render(WebExchangeBindException exception, ServerRequest request) {
Map<String, Set<String>> fieldErrorsMap = exception.getFieldErrors().stream()
.collect(Collectors.toMap(FieldError::getField, f -> Set.of(extractFieldErrorMsg(f)), Sets::union));
var fieldsErrors = fieldErrorsMap.entrySet().stream()
.map(e -> {
var err = new io.kafbat.ui.model.FieldErrorDTO();
err.setFieldName(e.getKey());
err.setRestrictions(List.copyOf(e.getValue()));
return err;
}).toList();
var message = fieldsErrors.isEmpty()
? exception.getMessage()
: "Fields validation failure";
var response = new ErrorResponseDTO()
.code(ErrorCode.BINDING_FAIL.code())
.message(message)
.requestId(requestId(request))
.timestamp(currentTimestamp())
.fieldsErrors(fieldsErrors)
.stackTrace(Throwables.getStackTraceAsString(exception));
return ServerResponse
.status(HttpStatus.BAD_REQUEST)
.contentType(MediaType.APPLICATION_JSON)
.headers(headers(request))
.bodyValue(response);
}
private Mono<ServerResponse> render(ResponseStatusException exception, ServerRequest request) {
String msg = coalesce(exception.getReason(), exception.getMessage(), "Server error");
var response = new ErrorResponseDTO()
.code(ErrorCode.UNEXPECTED.code())
.message(msg)
.requestId(requestId(request))
.timestamp(currentTimestamp())
.stackTrace(Throwables.getStackTraceAsString(exception));
return ServerResponse
.status(exception.getStatusCode())
.contentType(MediaType.APPLICATION_JSON)
.headers(headers(request))
.bodyValue(response);
}
private String requestId(ServerRequest request) {
return request.exchange().getRequest().getId();
}
private Consumer<HttpHeaders> headers(ServerRequest request) {
return (HttpHeaders headers) -> CorsGlobalConfiguration.fillCorsHeader(headers, request.exchange().getRequest());
}
private BigDecimal currentTimestamp() {
return BigDecimal.valueOf(System.currentTimeMillis());
}
private String extractFieldErrorMsg(FieldError fieldError) {
return coalesce(fieldError.getDefaultMessage(), fieldError.getCode(), "Invalid field value");
}
private <T> T coalesce(T... items) {
return Stream.of(items).filter(Objects::nonNull).findFirst().orElse(null);
}
}