Spring 带有自定义ErrorHandler的OAuth2RestTemplate

Spring 带有自定义ErrorHandler的OAuth2RestTemplate,spring,spring-security,spring-security-oauth2,Spring,Spring Security,Spring Security Oauth2,我已经配置了一个带有自定义错误处理程序的OAuth2RestTemplate,如果状态为4xx或5xx,我想用它禁用引发异常的默认行为(我想检查ResponseEntity本身的HttpStatus) 实现如下所示 @Bean public OAuth2RestTemplate restTemplate(OAuth2ProtectedResourceDetails resourceDetails) { OAuth2RestTemplate restTemplate = new OAuth

我已经配置了一个带有自定义错误处理程序的OAuth2RestTemplate,如果状态为4xx或5xx,我想用它禁用引发异常的默认行为(我想检查ResponseEntity本身的HttpStatus)

实现如下所示

@Bean
public OAuth2RestTemplate restTemplate(OAuth2ProtectedResourceDetails resourceDetails) {
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails);
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            // nothing to do
        }
    });
    return restTemplate;
}
当请求导致状态409(冲突)时,我总是得到以下异常:

org.springframework.web.client.ResourceAccessException:上的I/O错误 对“…”的POST请求:流已关闭; 嵌套异常为java.io.IOException:流已关闭

有没有办法避免这种例外情况?如果删除自定义错误处理程序,将出现HttpClientErrorException

org.springframework.web.client.HttpClientErrorException:409冲突

感谢您的回复:)

致以最良好的祝愿


Bernhard

通过创建OAuth2ErrorHandler的自定义子类,并使用该子类而不是自定义ResponseErrorHandler,我已经能够绕过引发的异常。OAuth2RestTemplate显式检查ErrorHandler是否为OAuth2ErrorHandler的实例

您只需重写hasError方法:

公共类NoOpResponseErrorHandler扩展了OAuth2ErrorHandler{
NoOpResponseErrorHandler(OAuth2ProtectedResourceDetails资源){
超级(资源);
}
@凌驾
公共布尔值hasError(ClientHttpResponse响应)引发IOException{
返回response.getStatusCode().equals(HttpStatus.UNAUTHORIZED)||
response.getStatusCode().equals(HttpStatus.FORBIDDEN);
}
}
要将其与
OAuth2RestTemplate
一起使用,您需要传入
OAuth2ProtectedResourceDetails
对象(即
ClientCredentialsResourceDetails


请参见

我认为您不需要扩展OAuth2ErrorHandler。您可以将自定义响应错误处理程序设置为OAuth2ErrorHandler实例:即restTemplate.setErrorHandler(新的OAuth2ErrorHandler(customErrorHandler,oAuthDetails());
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails);
restTemplate.setErrorHandler(new NoOpOAuthErrorHandler(resourceDetails));