[Spring Cloud] 解决Feign请求接口返回HttpStatus非200导致报错的问题

编程
83 0

OpenFeign 默认在请求接口后,如果接口返回的HTTP状态码非200范围,则会抛出 FeignException 的异常,但是这些接口有返回错误的数据,我希望将接口返回的错误信息原样返回给前端。

自定义 OpenFeign 的错误解码器:


@Configuration
@RequiredArgsConstructor
public class FeignErrorDecoder extends ErrorDecoder.Default {
    private final ObjectMapper objectMapper;

    @Override
    public Exception decode(String methodKey, Response response) {
        Exception exception = super.decode(methodKey, response);
        // 如果是 RetryableException,则返回继续重试
        if (exception instanceof RetryableException) {
            return exception;
        }

        try {
            // 如果是 FeignException,则对其进行处理,并抛出自身的业务异常
            if (exception instanceof FeignException && ((FeignException) exception).responseBody().isPresent()) {
                // 取出接口返回的数据
                ByteBuffer responseBody = ((FeignException) exception).responseBody().get();
                String bodyText = StandardCharsets.UTF_8.newDecoder().decode(responseBody.asReadOnlyBuffer()).toString();
                Result result = objectMapper.readValue(bodyText, Result.class);
                // 转为我们自身的异常类,并抛出去
                return new BizException(result.getCode(), result.getMessage(), HttpStatus.valueOf(response.status()));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return exception;
    }
}

再 @FeignClient 注解上配置 configuration:

@FeignClient(name = AppServiceNames.GOODS, path = "/goods", configuration = {FeignErrorDecoder.class})
最后更新 2022-09-14
评论 ( 0 )
OωO
隐私评论