[英]Using Spring RestTemplate, how can I log the response when there is an error?
Spring RestTemplate could set the errorHandler, which has the methods for handling errors. Spring RestTemplate可以设置errorHandler,它具有处理错误的方法。 I have an error handler like this
我有这样的错误处理程序
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(clientHttpResponse.getBody()))) {
final String response = buffer.lines().collect(Collectors.joining("\n"));
System.out.println(response);
}
but it always tell me that the input stream is close. 但是它总是告诉我输入流是关闭的。 Is this a bug or do I missing something?
这是错误还是我错过了什么?
The default error handler of RestTemplate DefaultResponseErrorHandler
already reads the response body and sets it in the HttpStatusCodeException
object that it throws. RestTemplate的默认错误处理程序
DefaultResponseErrorHandler
已经读取响应主体,并将其设置在HttpStatusCodeException
它抛出对象。
try {
restTemplate.getForObject("http://...", String.class);
} catch (HttpStatusCodeException e) {
System.out.println("Received error: " + e.getResponseBodyAsString());
}
If you want to always log the response body on error without requiring to catch HttpStatusCodeException
, you can extend the default error handler. 如果您想始终在错误上记录响应正文而无需捕获
HttpStatusCodeException
,则可以扩展默认错误处理程序。
public static class LoggingErrorHandler extends DefaultResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
try {
super.handleError(response);
} catch (HttpStatusCodeException e) {
System.out.println("Error response body is " + e.getResponseBodyAsString());
throw e;
}
}
}
Use the above error handler while instantiating rest template. 在实例化其余模板时使用上面的错误处理程序。
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new LoggingErrorHandler());
String response = restTemplate.getForObject("http://...", String.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.