我已经配置了一个带有自定义错误处理程序的 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 error on POST request for "http://localhost:10010/...": stream is closed; nested exception is java.io.IOException: stream is closed
有什么办法可以避免这个异常吗?如果我删除自定义错误处理程序,将会出现 HttpClientErrorException
org.springframework.web.client.HttpClientErrorException: 409 Conflict
感谢您的回复:)
最诚挚的问候,
伯恩哈德
最佳答案
我已经能够通过创建 OAuth2ErrorHandler 的自定义子类并使用它而不是自定义 ResponseErrorHandler 来解决抛出的异常。 OAuth2RestTemplate 显式检查 errorHandler 是否是 OAuth2ErrorHandler 的实例。
您应该只需要重写 hasError 方法:
public class NoOpResponseErrorHandler extends OAuth2ErrorHandler {
NoOpResponseErrorHandler(OAuth2ProtectedResourceDetails resource) {
super(resource);
}
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return response.getStatusCode().equals(HttpStatus.UNAUTHORIZED) ||
response.getStatusCode().equals(HttpStatus.FORBIDDEN);
}
}
要将其与 OAuth2RestTemplate
一起使用,您需要传入 OAuth2ProtectedResourceDetails
对象(即 ClientCredentialsResourceDetails
)。
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resourceDetails);
restTemplate.setErrorHandler(new NoOpOAuthErrorHandler(resourceDetails));
关于spring - 带有自定义 ErrorHandler 的 OAuth2RestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45924081/