0

我期待 302 带有一些包含我需要的数据的标头,因此我创建了一个 CustomErrorDecoder,但无法弄清楚如何在我的服务中获取标头。

public class FeignCustomErrorDecoder implements ErrorDecoder {
    private final ErrorDecoder errorDecoder = new Default();

    @Override
    public Exception decode(String methodKey, Response response){
        if (302 == response.status()){
            return new Response302Exception(response.reason(), response);
        }
        return errorDecoder.decode(methodKey, response);
    }
}
@AllArgsConstructor
@Data
public class Response302Exception extends Exception {

    private String reason;
    private Response response;
}
@EnableConfigurationProperties(AuthenticationClientProperties.class)
public class AuthenticationClientConfiguration {

    private static final int READTIMEOUTMILLIS = 10000;
    private static final int CONNECTTIMEOUTMILLIS = 5000;
    private static final boolean FOLLOWREDIRECTS = false;

    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor(AuthenticationClientProperties authClientProperties) {
        return new BasicAuthRequestInterceptor(authClientProperties.getLogin(), authClientProperties.getPassword());
    }

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

    @Bean
    public Request.Options options(){
        return new Request.Options(CONNECTTIMEOUTMILLIS, READTIMEOUTMILLIS, FOLLOWREDIRECTS);
    }

    @Bean
    @Primary
    @Scope("prototype")
    public Encoder feignFormEncoder() {
        return new FormEncoder();
    }
}

直到这里你可以看到 Feign 的配置,接下来你可以看到我的客户端和服务:

@FeignClient(name = "somename",
        configuration = AuthenticationClientConfiguration.class,
        decode404 = true,
        url = "${some url}"
        )
public interface OAuth2LoginClient {

    @PostMapping(value = "/login", consumes = APPLICATION_FORM_URLENCODED_VALUE)
    ResponseEntity<String> login(Map<String, ?> params);
}
    // Method inside the service, which calls to the client and needs some data from the headers in the 302 response.
    @Retryable({ SocketException.class, TimeoutException.class })
    public String oAuth2Login(LoginOAuth2Request request){
        try{
            ResponseEntity<String> responseEntity = oAuth2LoginClient.login(Map.of(
                    USERNAME, request.getUsername(),
                    PASSWORD, request.getPassword()
            ));
        }
        catch(Exception exception){
            // I was trying to get info with this catch, but it doesn't work. Also I cannot manage to throw my custom Response302Exception and catch it here.
        }
        return responseEntity.getHeaders().getInfoINeed();
    }

很简单,我只需要一个标题(一个字符串)中的数据。但是我不知道如何正确使用CustomErrorDecoder来获取服务中我需要的数据。

4

0 回答 0