全局异常处理器

First Post:

Last Update:

Word Count:
753

Read Time:
4 min

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
@Slf4j
@RestControllerAdvice(basePackages = {"info.wangyuan.enroll.controller", "info.wangyuan.enroll.controller.admin"})
public class GlobalExceptionHandler {

@ExceptionHandler(Throwable.class)
public Result elegantlyHandleException(HttpServletRequest request, Exception e) {
try {
log.error("--------------- {} start ---------------", e.getClass().getSimpleName());
prettyPrintRequestInfo(request);
log.error(e.getMessage(), e);
log.error("--------------- {} end ---------------", e.getClass().getSimpleName());
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
return Result.fail(StatusCodeEnum.UNKNOWN_ERROR);
}

@ExceptionHandler(BusinessException.class)
public Result handleBusinessException(HttpServletRequest request, BusinessException e) {
try {
log.error("--------------- {} start ---------------", e.getClass().getSimpleName());
prettyPrintRequestInfo(request);
log.error(e.getMessage());
log.error("--------------- {} end ---------------", e.getClass().getSimpleName());
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
return Result.fail(e.getCode(), e.getMessage());
}

@ExceptionHandler(BindException.class)
public Result handleBindException(HttpServletRequest request, BindException e) {
try {
log.error("--------------- {} start ---------------", e.getClass().getSimpleName());
prettyPrintRequestInfo(request);
log.error(e.getMessage());
log.error("--------------- {} end ---------------", e.getClass().getSimpleName());
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
StringJoiner messageJoiner = new StringJoiner("\n");
e.getFieldErrors().stream().forEach(fieldError -> {
messageJoiner.add(fieldError.getDefaultMessage());
});
return Result.fail(StatusCodeEnum.PARAMETER_ERROR.getCode(), messageJoiner.toString());
}

@ExceptionHandler(MethodArgumentNotValidException.class)
public Result handleMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException e) {
try {
log.error("--------------- {} start ---------------", e.getClass().getSimpleName());
prettyPrintRequestInfo(request);
log.error(e.getMessage());
log.error("--------------- {} end ---------------", e.getClass().getSimpleName());
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}

StringJoiner messageJoiner = new StringJoiner(";");
e.getBindingResult().getFieldErrors().stream().forEach(fieldError -> {
messageJoiner.add(fieldError.getDefaultMessage());
});
return Result.fail(StatusCodeEnum.PARAMETER_ERROR.getCode(), messageJoiner.toString());
}

@ExceptionHandler(HttpMessageNotReadableException.class)
public Result handleHttpMessageNotReadableException(HttpServletRequest request, HttpMessageNotReadableException e) {
try {
log.error("--------------- {} start ---------------", e.getClass().getSimpleName());
prettyPrintRequestInfo(request);
log.error(e.getMessage());
log.error("--------------- {} end ---------------", e.getClass().getSimpleName());
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}

return Result.fail(StatusCodeEnum.PARAMETER_ERROR);
}

@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Result handleHttpRequestMethodNotSupportedException(HttpServletRequest request, HttpRequestMethodNotSupportedException e) {
try {
log.error("--------------- {} start ---------------", e.getClass().getSimpleName());
prettyPrintRequestInfo(request);
log.error(e.getMessage());
log.error("--------------- {} end ---------------", e.getClass().getSimpleName());
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}

return Result.fail(StatusCodeEnum.REQUEST_METHOD_NOT_SUPPORT);
}

@ExceptionHandler(ConstraintViolationException.class)
public Result handleConstraintViolationException(HttpServletRequest request, ConstraintViolationException e) {
try {
log.error("--------------- {} start ---------------", e.getClass().getSimpleName());
prettyPrintRequestInfo(request);
log.error(e.getMessage());
log.error("--------------- {} end ---------------", e.getClass().getSimpleName());
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}

StringBuilder sb = new StringBuilder();
Iterator<ConstraintViolation<?>> iterator = e.getConstraintViolations().iterator();
while (iterator.hasNext()) {
ConstraintViolation<?> cv = iterator.next();
sb.append(cv.getMessage());

if (iterator.hasNext()) {
sb.append(";");
}
}
return Result.fail(StatusCodeEnum.PARAMETER_ERROR.getCode(), sb.toString());
}

@ExceptionHandler(MissingServletRequestParameterException.class)
public Result handleMissingServletRequestParameterException(HttpServletRequest request, MissingServletRequestParameterException e) {
try {
log.error("--------------- {} start ---------------", e.getClass().getSimpleName());
prettyPrintRequestInfo(request);
log.error(e.getMessage());
log.error("--------------- {} end ---------------", e.getClass().getSimpleName());
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
return Result.fail(StatusCodeEnum.PARAMETER_ERROR.getCode(), "缺少参数: " + e.getParameterName());
}

/**
* 打印请求信息, 方便用于复查
*
* @param request
*/
public void prettyPrintRequestInfo(HttpServletRequest request) {
String requestURI = request.getRequestURI();
String method = request.getMethod();
Map<String, String[]> parameterMap = request.getParameterMap();
Map<String, List<String>> printedMap = convertToStringKeyAndListValue(parameterMap);
String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE);
log.error("请求uri: {}", requestURI);
log.error("请求方法: {}", method);
log.error("请求参数: {}", printedMap);
log.error("请求头Content-Type: {}", contentType);
}

private Map<String, List<String>> convertToStringKeyAndListValue(Map<String, String[]> parameterMap) {
Map<String, List<String>> map = new HashMap<>(parameterMap.size());
parameterMap.forEach((key, value) -> {
map.put(key, Arrays.stream(value).map(this::truncateString).collect(Collectors.toList()));
});
return map;
}

private String truncateString(String str) {
if (str == null) {
return null;
} else if (str.length() > 300) {
return str.substring(0, 300);
} else {
return str;
}
}
}