ResultStatusDecoder.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package com.fdkankan.common.config;
  2. import com.alibaba.cloud.commons.io.IOUtils;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.fdkankan.common.constant.ServerCode;
  5. import com.fdkankan.common.exception.BusinessException;
  6. import com.fdkankan.common.response.ResultData;
  7. import feign.Response;
  8. import feign.codec.Decoder;
  9. import lombok.extern.slf4j.Slf4j;
  10. import java.io.IOException;
  11. import java.lang.reflect.Type;
  12. import java.nio.charset.StandardCharsets;
  13. import java.util.Objects;
  14. @Slf4j
  15. public final class ResultStatusDecoder implements Decoder {
  16. public static final String CONTENT_KEY = "content";
  17. final Decoder delegate;
  18. public ResultStatusDecoder(Decoder delegate) {
  19. Objects.requireNonNull(delegate, "Decoder must not be null. ");
  20. this.delegate = delegate;
  21. }
  22. @Override
  23. public Object decode(Response response, Type type) throws IOException {
  24. // 判断是否返回参数是否是异常
  25. String resultStr = IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8);
  26. log.info("feign调用返回,result msg ->{}",resultStr);
  27. try {
  28. ResultData resultData = JSONObject.parseObject(resultStr, ResultData.class);
  29. if(resultData.getCode() != ServerCode.SUCCESS.code()){
  30. throw new BusinessException(resultData.getCode(),resultData.getMessage());
  31. }
  32. }catch (Exception e){
  33. e.printStackTrace();
  34. }
  35. // 回写body
  36. return delegate.decode(response.toBuilder().body(resultStr, StandardCharsets.UTF_8).build(), type);
  37. }
  38. }