-
Notifications
You must be signed in to change notification settings - Fork 330
/
ErrorDecoderInterceptor.java
67 lines (59 loc) · 2.34 KB
/
ErrorDecoderInterceptor.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
package com.github.lianjiatech.retrofit.spring.boot.interceptor;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Objects;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotatedElementUtils;
import com.github.lianjiatech.retrofit.spring.boot.core.ErrorDecoder;
import com.github.lianjiatech.retrofit.spring.boot.core.RetrofitClient;
import com.github.lianjiatech.retrofit.spring.boot.util.AppContextUtils;
import lombok.SneakyThrows;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Invocation;
/**
* @author 陈添明
*/
public class ErrorDecoderInterceptor implements Interceptor, ApplicationContextAware {
protected ApplicationContext applicationContext;
@Override
@SneakyThrows
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Method method = Objects.requireNonNull(request.tag(Invocation.class)).method();
RetrofitClient retrofitClient =
AnnotatedElementUtils.findMergedAnnotation(method.getDeclaringClass(), RetrofitClient.class);
ErrorDecoder errorDecoder =
AppContextUtils.getBeanOrNew(applicationContext, retrofitClient.errorDecoder());
boolean decoded = false;
try {
Response response = chain.proceed(request);
if (errorDecoder == null) {
return response;
}
decoded = true;
Exception exception = errorDecoder.invalidRespDecode(request, response);
if (exception == null) {
return response;
}
throw exception;
} catch (IOException e) {
if (decoded) {
throw e;
}
throw errorDecoder.ioExceptionDecode(request, e);
} catch (Exception e) {
if (decoded && e instanceof RuntimeException) {
throw (RuntimeException)e;
}
throw errorDecoder.exceptionDecode(request, e);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}