wuxw
2019-04-25 d4e1929dcab147030d3bcae89b1801250fd6a5da
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
package com.java110.core.feign;
 
 
import com.netflix.hystrix.exception.HystrixBadRequestException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import java.io.IOException;
 
/**
 * 自定义异常解析
 */
public class UserErrorDecoder implements ErrorDecoder {
 
    private static final int HTTP_STATUS_400 = 400;
 
    private Logger logger = LoggerFactory.getLogger(getClass());
 
    /**
     * 异常解析 在 SynchronousMethodHandler 类 134 号调用
     *
     * @param methodKey 方法key
     * @param response  返回对象
     * @return 返回异常
     */
    public Exception decode(String methodKey, Response response) {
 
        Exception exception = null;
        try {
            String json = Util.toString(response.body().asReader());
 
            logger.error("调用方法出现异常了:" + json);
            exception = new RuntimeException(json);
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex);
        }
        // 这里只封装4开头的请求异常ß && response.status() < 500
        if (HTTP_STATUS_400 <= response.status()) {
            exception = new HystrixBadRequestException("请求参数错误:", exception);
        } else {
            logger.error(exception.getMessage(), exception);
        }
        return exception;
    }
}