为什么当休息模板抛出异常时,自定义休息错误处理程序没有被调用?

Poo*_*ain 6 resttemplate custom-error-handling spring-boot

我试图涵盖类中所有其余的模板调用以进行异常处理。在 Spring Boot 应用程序中使用自定义异常处理和错误处理程序。

为此,我在配置中创建了一个休息模板 bean,并将其中的错误处理程序设置为我使用扩展 DefaultResponseErrorHandler 创建的自定义错误处理程序类。

public class BaseConfig {
@Bean
    @Primary
    RestTemplate restTemplate(@Autowired RestTemplateBuilder restTemplateBuilder) {
        return restTemplateBuilder.errorHandler(new IPSRestErrorHandler()).build();
    }
}
Run Code Online (Sandbox Code Playgroud)
@Component
public class IPSRestErrorHandler extends DefaultResponseErrorHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(IPSRestErrorHandler.class);

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        if (response.getStatusCode()
                .series() == HttpStatus.Series.SERVER_ERROR) {
            LOGGER.error("Server error with exception code  : "+response.getStatusCode()+" with message : "+response.getStatusText());
            throw ExceptionUtils.newRunTimeException("Server error with exception code  : "+response.getStatusCode()+" with message : "+response.getStatusText());
        } else if (response.getStatusCode()
                .series() == HttpStatus.Series.CLIENT_ERROR) {
            LOGGER.error("Client error with exception code  : "+response.getStatusCode()+" with message : "+response.getStatusText());
            throw ExceptionUtils.newRunTimeException("Client error with exception code  : "+response.getStatusCode()+" with message : "+response.getStatusText());
        } else {
            LOGGER.error("Unknown HttpStatusCode with exception code  : "+response.getStatusCode()+" with message : "+response.getStatusText());
            throw ExceptionUtils.newRunTimeException("Unknown HttpStatusCode with exception code  : "+response.getStatusCode()+" with message :"+response.getStatusText());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
public class ServicingPlatformSteps {

 @Autowired
    private RestTemplate restTemplate;

 private ResponseEntity callServicingPlatformAPI(RemittanceV2Input inputClass) {
ResponseEntity entity = null;
entity = restTemplate.exchange(builder.build().encode().toUri(),
                    org.springframework.http.HttpMethod.POST, httpEntity, typeRef);
return entity;
}
Run Code Online (Sandbox Code Playgroud)

在这里,我期望当调用restTemplate.exchange方法并抛出一些异常时,应该调用我的IPSRestErrorHandler。但错误处理程序没有被调用。当我得到这个带有错误处理程序信息的restTemplate实例时。

您能帮我解释为什么错误处理程序没有被调用吗?

Viv*_*vek 0

在你的情况下替换下面

@Component
public class IPSRestErrorHandler extends DefaultResponseErrorHandler {

}
Run Code Online (Sandbox Code Playgroud)

@Component
public class IPSRestErrorHandler extends ResponseErrorHandler {

}
Run Code Online (Sandbox Code Playgroud)

请参阅,ResponseErrorHandler将确保HTTP statusresponse被读取。所以我们也必须extend这样做。

并且您已经将实现注入IPSRestErrorHandlerRestTemplate实例中。

您可以在此处阅读更多内容,它还解释了如何进行单元测试。

希望能帮助到你。