使用 RestControllerAdvice 处理 Spring boot 中的 feign 异常

问题描述 投票:0回答:1

我有一些 Fiegn 客户端来发送请求其他 springboot 微服务。

 @ExceptionHandler(FeignException.class)
    public ResponseEntity<ApiError> handleFeignException(FeignException ex, WebRequest webRequest) throws JsonProcessingException {
           try{
            ObjectMapper objectMapper = JsonMapper.builder()
                    .findAndAddModules()
                    .build();
            ApiError apiError = objectMapper.readValue(ex.contentUTF8(), ApiError.class);
               return new ResponseEntity<>(apiError, HttpStatusCode.valueOf(ex.status()));
    
        } catch (JsonProcessingException e) {
            log.error("Error deserializing Feign exception: {}", e.getMessage());
            ApiError fallbackError = new ApiError("Error deserializing Feign exception", LocalDate.now(), ex.status(), webRequest.getDescription(false));
            return ResponseEntity.status(HttpStatusCode.valueOf(ex.status()))
                    .body(fallbackError);
        }
    }
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString
public class ApiError {
    private String message;
    private LocalDate timeStamp;
    private int status;
    private String requestPath;
}

所以我正在以这种方式处理 Spring Boot 微服务之间的服务间通信期间由 feign 客户端抛出的 feign 异常...是否还有其他好的方法或者我是否以正确的方式进行操作

java spring-boot microservices spring-cloud spring-cloud-feign
1个回答
0
投票

您拥有的是另一种处理异常的方法,但我可以建议您根据

自定义错误处理
进行自定义ErrorDecoder 在 OpenFeign 的 wiki 页面上。

举个例子:

public class CustomErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.status() >= 400 && response.status() <= 499) {
            return new StashClientException(
                    response.status(),
                    response.reason()
            );
        }
        if (response.status() >= 500 && response.status() <= 599) {
            return new StashServerException(
                    response.status(),
                    response.reason()
            );
        }
        return errorStatus(methodKey, response);
    }
}

声明它创建一个配置类后,除了

ErrorDecoder
你还可以在这个类中声明:自定义过滤器、拦截器。

@Configuration
public class MyFeignClientConfiguration {

    @Bean
    public ErrorDecoder errorDecoder() {
        return new CustomErrorDecoder();
    }
}

在 Feign 界面中你将拥有:

@FeignClient(
    value = "myFeignClient", 
    configuration = MyFeignClientConfiguration.class
)
© www.soinside.com 2019 - 2024. All rights reserved.