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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
|
package com.zx.alice.exception;
import jakarta.validation.ValidationException;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.*;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.Nullable;
import org.springframework.validation.method.MethodValidationException;
import org.springframework.web.*;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.method.annotation.HandlerMethodValidationException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import org.springframework.web.servlet.resource.NoResourceFoundException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* 全局异常处理 RFC-9457
*/
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@Nullable
@Override
public ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
pageNotFoundLogger.warn(ex.getMessage());
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleHttpMediaTypeNotSupported(HttpMediaTypeNotSupportedException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleHttpMediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleMissingPathVariable(MissingPathVariableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleMissingServletRequestPart(MissingServletRequestPartException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleServletRequestBindingException(ServletRequestBindingException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
Object[] args = ex.getDetailMessageArguments();
assert args != null;
String defaultDetail = args[0] + "" + args[1];
ProblemDetail body = this.createProblemDetail(ex, status, defaultDetail, (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleHandlerMethodValidationException(HandlerMethodValidationException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleNoResourceFoundException(NoResourceFoundException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleAsyncRequestTimeoutException(AsyncRequestTimeoutException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleErrorResponseException(ErrorResponseException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
/**
* 较低级别的异常,以及在客户端和服务器上对称使用的异常
*/
@Nullable
@Override
public ResponseEntity<Object> handleConversionNotSupported(ConversionNotSupportedException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
Object[] args = {ex.getPropertyName(), ex.getValue()};
String defaultDetail = "Failed to convert '" + args[0] + "' with value: '" + args[1] + "'";
ProblemDetail body = this.createProblemDetail(ex, status, defaultDetail, null, args, request);
return handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
Object[] args = {ex.getPropertyName(), ex.getValue()};
String defaultDetail = "Failed to convert '" + args[0] + "' with value: '" + args[1] + "'";
String messageCode = ErrorResponse.getDefaultDetailMessageCode(TypeMismatchException.class, null);
ProblemDetail body = this.createProblemDetail(ex, status, defaultDetail, messageCode, args, request);
return handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleHttpMessageNotWritable(HttpMessageNotWritableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ProblemDetail body = this.createProblemDetail(ex, status, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, status, request);
}
@Nullable
@Override
public ResponseEntity<Object> handleMethodValidationException(MethodValidationException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
ProblemDetail body = createProblemDetail(ex, status, ex.getLocalizedMessage(), null, null, request);
return handleExceptionInternal(ex, body, headers, status, request);
}
/**
* spring未管理的异常
*/
@ExceptionHandler(ValidationException.class)
public ResponseEntity<Object> handleValidationException(ValidationException ex, WebRequest request) {
HttpHeaders headers = new HttpHeaders();
ProblemDetail body = this.createProblemDetail(ex, HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, HttpStatus.BAD_REQUEST, request);
}
@ExceptionHandler(ResponseStatusException.class)
public ResponseEntity<Object> handleResponseStatusException(ResponseStatusException ex, WebRequest request) {
HttpHeaders headers = new HttpHeaders();
ProblemDetail body = this.createProblemDetail(ex, ex.getStatusCode(), Optional.ofNullable(ex.getReason()).orElse(""), (String) null, (Object[]) null, request);
return this.handleExceptionInternal(ex, body, headers, ex.getStatusCode(), request);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleException2(Exception ex, WebRequest request) {
HttpHeaders headers = new HttpHeaders();
ProblemDetail body = this.createProblemDetailControlLogLevel(ex, HttpStatus.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage(), (String) null, (Object[]) null, request, "error");
return this.handleExceptionInternal(ex, body, headers, HttpStatus.INTERNAL_SERVER_ERROR, request);
}
@Override
protected ProblemDetail createProblemDetail(Exception ex, HttpStatusCode status,
String defaultDetail, @Nullable String detailMessageCode, @Nullable Object[] detailMessageArguments,
WebRequest request) {
return createProblemDetailControlLogLevel(ex, status, defaultDetail, detailMessageCode, detailMessageArguments, request, "warn");
}
protected ProblemDetail createProblemDetailControlLogLevel(Exception ex, HttpStatusCode status,
String defaultDetail, @Nullable String detailMessageCode, @Nullable Object[] detailMessageArguments,
WebRequest request, String logLevel) {
ProblemDetail problemDetail = super.createProblemDetail(ex, status, defaultDetail, detailMessageCode, detailMessageArguments, request);
problemDetail.setProperty("exception", ex.getClass().getName());
problemDetail.setProperty("timestamp", ZonedDateTime.now().withZoneSameInstant(ZoneId.of("Asia/Shanghai")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")));
// problemDetail.setProperty("stackTrace", getStackTraceAsJsonArray(ex));
if (this.logger.isWarnEnabled() && "warn".equals(logLevel)) {
this.logger.warn("发生warn级别异常: ", ex);
}
if (this.logger.isErrorEnabled() && "error".equals(logLevel)) {
this.logger.warn("发生error级别异常: ", ex);
}
return problemDetail;
}
private List<String> getStackTraceAsJsonArray(Throwable throwable) {
List<String> stackTrace = new ArrayList<>();
for (StackTraceElement element : throwable.getStackTrace()) {
stackTrace.add(element.toString());
}
return stackTrace;
}
}
|