GlobalResponseAdvice.java
1.93 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
package top.panll.assist.config;
import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import top.panll.assist.controller.bean.ErrorCode;
import top.panll.assist.controller.bean.WVPResult;
import javax.validation.constraints.NotNull;
/**
* 全局统一返回结果
* @author lin
*/
@RestControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(@NotNull MethodParameter returnType, @NotNull Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, @NotNull MethodParameter returnType, @NotNull MediaType selectedContentType, @NotNull Class<? extends HttpMessageConverter<?>> selectedConverterType, @NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response) {
// 排除api文档的接口,这个接口不需要统一
String[] excludePath = {"/v3/api-docs","/api/v1","/index/hook"};
for (String path : excludePath) {
if (request.getURI().getPath().startsWith(path)) {
return body;
}
}
if (body instanceof WVPResult) {
return body;
}
if (body instanceof ErrorCode) {
ErrorCode errorCode = (ErrorCode) body;
return new WVPResult<>(errorCode.getCode(), errorCode.getMsg(), null);
}
if (body instanceof String) {
return JSON.toJSONString(WVPResult.success(body));
}
return WVPResult.success(body);
}
}