【发布时间】:2021-08-01 12:11:35
【问题描述】:
- 我正在为应用程序中的所有 RestTemplate api 调用编写自定义 ResponseErrorHandler。此应用是一个 Spring Boot 应用,使用 Kotlin 编写
我的代码:
ServiceApiErrorHandler.class
class ServiceApiErrorHandler(
@Autowired
val agentAuthService: AgentAuthService
) : DefaultResponseErrorHandler() {
companion object {
private val logger: LogService = LogServiceImpl(ServiceApiErrorHandler::class.java)
}
override fun hasError(response: ClientHttpResponse): Boolean {
return (response.statusCode.is4xxClientError || response.statusCode.is5xxServerError)
}
override fun handleError(response: ClientHttpResponse) {
logger.info("LOGIN AGAIN 1")
}
override fun handleError(url: URI, method: HttpMethod, response: ClientHttpResponse) {
if (response.statusCode == HttpStatus.UNAUTHORIZED && ServiceApiEnpoint.isServiceApiEndpoint(url = url.toString())) {
logger.info("LOGIN AGAIN")
agentAuthService.callLogin();
}
}
}
CustomRestTemplateCustomizer 类
class CustomRestTemplateCustomizer(
@Autowired
val agentAuthService: AgentAuthService
) : RestTemplateCustomizer {
override fun customize(restTemplate: RestTemplate) {
restTemplate.errorHandler = ServiceApiErrorHandler(agentAuthService = agentAuthService)
}
}
ClientHttpConfig 类
@Configuration
class ClientHttpConfig(
@Autowired
val agentAuthService: AgentAuthService
) {
@Bean
fun customRestTemplateCustomizer(): CustomRestTemplateCustomizer {
return CustomRestTemplateCustomizer(agentAuthService = agentAuthService);
}
}
问题是当我运行时,RestTemplate 仍然使用 DefaultResponseErrorHandler 处理错误,调试后,我很快意识到 CustomRestTemplateCustomizer 类中的 customize() 方法从未被调用。
所以我的问题是:
- custom() 方法是否应该是自动调用的?如果不是,我应该怎么称呼它?
- 我的代码可以实现自定义的ResponseErrorHandler吗?
注意:我按照 Java 教程:https://www.baeldung.com/spring-rest-template-builder 用 Kotlin 编写此版本。
【问题讨论】:
标签: java spring spring-boot kotlin resttemplate