1
1
package org .geekbang .time .commonmistakes .apidesign .apiresponse ;
2
2
3
+ import com .fasterxml .jackson .databind .ObjectMapper ;
4
+ import lombok .SneakyThrows ;
3
5
import lombok .extern .slf4j .Slf4j ;
6
+ import org .springframework .beans .factory .annotation .Autowired ;
4
7
import org .springframework .core .MethodParameter ;
5
8
import org .springframework .core .annotation .AnnotationUtils ;
6
9
import org .springframework .http .MediaType ;
9
12
import org .springframework .http .server .ServerHttpResponse ;
10
13
import org .springframework .web .bind .annotation .ExceptionHandler ;
11
14
import org .springframework .web .bind .annotation .RestControllerAdvice ;
15
+ import org .springframework .web .servlet .NoHandlerFoundException ;
12
16
import org .springframework .web .servlet .mvc .method .annotation .ResponseBodyAdvice ;
13
17
14
18
import javax .servlet .http .HttpServletRequest ;
15
19
16
20
@ RestControllerAdvice
17
21
@ Slf4j
18
22
public class APIResponseAdvice implements ResponseBodyAdvice <Object > {
23
+ @ Autowired
24
+ private ObjectMapper objectMapper ;
19
25
20
26
//自动处理APIException,包装为APIResponse
21
27
@ ExceptionHandler (APIException .class )
@@ -28,6 +34,16 @@ public APIResponse handleApiException(HttpServletRequest request, APIException e
28
34
return apiResponse ;
29
35
}
30
36
37
+ @ ExceptionHandler (NoHandlerFoundException .class )
38
+ public APIResponse handleException (NoHandlerFoundException ex ) {
39
+ log .error (ex .getMessage (), ex );
40
+ APIResponse apiResponse = new APIResponse ();
41
+ apiResponse .setSuccess (false );
42
+ apiResponse .setCode (4000 );
43
+ apiResponse .setMessage (ex .getMessage ());
44
+ return apiResponse ;
45
+ }
46
+
31
47
//仅当方法或类没有标记@NoAPIResponse才自动包装
32
48
@ Override
33
49
public boolean supports (MethodParameter returnType , Class converterType ) {
@@ -37,13 +53,20 @@ public boolean supports(MethodParameter returnType, Class converterType) {
37
53
}
38
54
39
55
//自动包装外层APIResposne响应
56
+ @ SneakyThrows
40
57
@ Override
41
58
public Object beforeBodyWrite (Object body , MethodParameter returnType , MediaType selectedContentType , Class <? extends HttpMessageConverter <?>> selectedConverterType , ServerHttpRequest request , ServerHttpResponse response ) {
42
59
APIResponse apiResponse = new APIResponse ();
43
60
apiResponse .setSuccess (true );
44
61
apiResponse .setMessage ("OK" );
45
62
apiResponse .setCode (2000 );
46
63
apiResponse .setData (body );
47
- return apiResponse ;
64
+ if (body instanceof String ) {
65
+ response .getHeaders ().setContentType (MediaType .APPLICATION_JSON );
66
+ return objectMapper .writeValueAsString (apiResponse );
67
+ } else {
68
+ return apiResponse ;
69
+ }
70
+
48
71
}
49
72
}
0 commit comments