如何使用错误解码器抛出异常/获取数据-openfeign

vyswwuz2  于 2021-07-23  发布在  Java
关注(0)|答案(0)|浏览(249)

我期望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();
    }
}

在这里您可以看到外部配置之前,接下来您可以看到我的客户机和服务:

@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来获取服务中所需的数据。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题