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

问题描述 投票:1回答:1

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

为此,我在config中创建了一个rest模板bean,并在其中设置了错误处理程序到我使用extends DefaultResponseErrorHandler创建的自定义错误处理程序类。

public class BaseConfig {
@Bean
    @Primary
    RestTemplate restTemplate(@Autowired RestTemplateBuilder restTemplateBuilder) {
        return restTemplateBuilder.errorHandler(new IPSRestErrorHandler()).build();
    }
}
@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());
        }
    }
}
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;
}

在这里,我期待当调用restTemplate.exchange方法并且它抛出一些异常时,应该调用我的IPSRestErrorHandler。但错误处理程序没有被调用。虽然我正在使用错误处理程序信息获取此restTemplate实例。

你能不能帮我解决为什么没有调用错误处理程序?

spring-boot resttemplate custom-error-handling
1个回答
0
投票

在你的情况下,替换下面

@Component
public class IPSRestErrorHandler extends DefaultResponseErrorHandler {

}

@Component
public class IPSRestErrorHandler extends ResponseErrorHandler {

}

请注意,ResponseErrorHandler将确保阅读来自HTTP statusresponse。所以我们必须extend相同。

你已经将IPSRestErrorHandler实现注入了RestTemplate实例。

你可以阅读更多here,它解释了你如何进行单元测试。

希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.