feign服务器响应数据量过大,spring cloud中feign调用服务端捕获异常详情

问题

feign调用后,服务端返回FeignExecption:500 FeignClient.FunctionName

FeignClient添加配置处理类

@FeignClient(value = "serviceName",configuration = FeignExceptionConfiguration.class)

实现fegin的异常处理类,具体实现类:

import feign.Util;

import feign.codec.ErrorDecoder;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;

import org.codehaus.jackson.map.DeserializationConfig;

import org.codehaus.jackson.map.ObjectMapper;

import org.codehaus.jackson.map.annotate.JsonSerialize;

import org.springframework.context.annotation.Bean;

@Slf4j

public class FeignExceptionConfiguration {

@Bean

public ErrorDecoder errorDecoder() {

return new UserErrorDecoder();

}

/**

* 重新实现feign的异常处理,捕捉restful接口返回的json格式的异常信息

*

*/

public class UserErrorDecoder implements ErrorDecoder {

@Override

public Exception decode(String methodKey, Response response) {

Exception exception = null;

ObjectMapper mapper = new ObjectMapper();

//空属性处理

mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);

//设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性

mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);

//禁止使用int代表enum的order来反序列化enum

mapper.configure(DeserializationConfig.Feature.FAIL_ON_NUMBERS_FOR_ENUMS, true);

try {

String json = Util.toString(response.body().asReader());

exception = new RuntimeException(json);

if (StringUtils.isEmpty(json)) {

return null;

}

FeignFaildResult result = mapper.readValue(json, FeignFaildResult.class);

// 业务异常包装成自定义异常类MyException

if (result.getStatus() != HttpStatus.OK.value()) {

exception = new MyException(result.getMessage(),result.getStatus());

}

} catch (IOException ex) {

log.error(ex.getMessage(), ex);

}

return exception;

}

}

}

异常json数据格式化java对象:

String json = Util.toString(response.body().asReader());

/**

* 根据 json 来定义需要的字段

*/

@Data

public class FeignFaildResult {

private String message;

private int status;

}

这么一来,服务端返回的异常就可以在调用端统一封装为自定义异常类MyException

public class MyException extends RuntimeException {

// 自定义异常代码

private int status = 503;

// 构造方法

public MyException(String message, int status) {

super(message);

this.status = status;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值