目录
  • FeignClient服务器抛出异常客户端处理
    • feign异常拦截器
  • FeignClient异常合集Mark
    • 问题1
    • 问题2

FeignClient服务器抛出异常客户端处理

在使用feign进行远程方法调用时,如果远程服务端方法出现异常,客户端有时需要捕获,并且把异常信息返回给前端,而如果在开启熔断之后,这个异常会被消化,所以说,如果希望拿到服务端异常,

feign.hystrix.enable需要设置为false,而当不开熔断时,我们也有几种方法把拿到服务端的异常信息,下面总结一下。

feign异常拦截器

注册一个Bean对象,当feign调用出现异常的时候,会触发这个方法:

import com.test.JsonUtils;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import io.test.BadRequestException;
import io.test.InternalServerErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static feign.FeignException.errorStatus;

/**
 * @author 飘逝才子
 * @date 2020/11/05
 * @description
 */
@Configuration
public class FeignClientErrorDecoder implements ErrorDecoder {
    private Logger logger = LoggerFactory.getLogger(FeignClientErrorDecoder.class);

    @Override
    public Exception decode(String methodKey, Response response) {
        Map<String, Object> jsonBody = new HashMap<>();
        jsonBody.put("message", "Internal server error");
        try {
            String body = Util.toString(response.body().asReader());
            jsonBody = JsonUtils.toMap(body);
        } catch (IOException e) {
            logger.error("feign.IOException", e);
        }
        assert jsonBody != null;
        if (response.status() >= 400 && response.status() < 500) {
            throw new BadRequestException(jsonBody.get("message").toString());
        }

        if (response.status() >= 500) {
            throw new InternalServerErrorException(jsonBody.get("message").toString());
        }

        return errorStatus(methodKey, response);
    }
}

注意,使用这个方式,需要在熔断器关闭时才起作用,因为它们的执行过程是,先走这个拦截器,再走熔断的fallback,所以这个异常会被熔断吞掉,返回状态为200,返回值为你的fallback的默认值。

FeignClient异常合集Mark

问题1

feignClient调用报异常cause:Content-Type cannot contain wildcard type ‘*’

是因为远程调用的时候入参识别不了application/json

解决办法:在方法上加上类型即可consumes = MediaType.APPLICATION_JSON_VALUE

 @RequestMapping(value = "/xxx/xxx/xxx/xxx/xxx/xxx/result",method = RequestMethod.GET,  consumes = MediaType.APPLICATION_JSON_VALUE)
    ResponseResult xxx(TaskParam taskParam);

问题2

fallback 与fallbackFactory的使用

fallbackFactory:抛出异常可查看,一般看里面抛出的异常日志即可判断远程调用的问题所在。

FeignClient服务器抛出异常客户端处理方案

FeignClient服务器抛出异常客户端处理方案

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。