这是一个简单的类,我试图用@value 映射错误消息。
我没有在属性文件中添加相应的值,因为我设置了默认值
@Slf4j
@Component
public class RestTemplateResponseErrorHandler
implements ResponseErrorHandler {
@Value("${invalid.password:test}")
private String invalidPassword;
@Override
public boolean hasError(ClientHttpResponse httpResponse)
throws IOException {
return (
httpResponse.getStatusCode().series() == CLIENT_ERROR
|| httpResponse.getStatusCode().series() == SERVER_ERROR);
}
@Override
public void handleError(ClientHttpResponse httpResponse)
throws IOException {
if (httpResponse.getStatusCode()
.series() == SERVER_ERROR) {
log.info("RestTemplateResponseErrorHandler --- SERVER_ERROR");
// handle SERVER_ERROR
} else if (httpResponse.getStatusCode()
.series() == CLIENT_ERROR) {
log.info("RestTemplateResponseErrorHandler --- CLIENT_ERROR");
if (httpResponse.getStatusCode() == HttpStatus.BAD_REQUEST)
throw new UnAuthorisedRequestException(invalidPassword);
}
}
}
这里抛出新的 UnAuthorisedRequestException(invalidPassword); 返回空
不确定该类有什么问题,因为它被标记为@Component
@Configuration
public class CommonBeanConfig {
@Bean
public RestTemplate restTemplate(SSLSocketFactory sslSocketFactory) {
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(new SSLConnectionSocketFactory(sslSocketFactory, new NoopHostnameVerifier()))
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(requestFactory));
restTemplate.setInterceptors(Collections.singletonList(new ClientLoggingInterceptor()));
restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());
return restTemplate;
}
}
此类被添加为异常处理程序