我们对在 gui 应用程序中运行的服务器进行了改造 java 客户端,我们希望在没有连接到服务器时通知用户,有一些明显的异常,如 ConnectException 或 UnknownHostException 等。 但在超时时我们不想什么都不做,下一次 api 调用可能会成功。 我的主要问题是关于 SocketTimeoutException,什么时候意味着服务器无法访问? 有时消息是“连接超时”,有时是“超时”
那么如何区分超时和服务器无法访问?
现在我已经编写了这段代码:
public static boolean isConnectionUnavailableException(@NotNull Throwable exception) {
//these are considered just timeout
if ((SocketTimeoutException.class.equals(exception.getClass()) && !isConnectTimeout(exception)) ||
HttpTimeoutException.class.equals(exception.getClass()) ||
isIOExceptionTimeout(exception)) {
return false;
}
return isConnectTimeout(exception) ||
isConnectionIssueErrorCode(exception) ||
exception instanceof SocketException ||
exception instanceof UnknownHostException ||
exception instanceof HttpConnectTimeoutException ||
exception instanceof InterruptedIOException;
}
private static boolean isConnectionIssueErrorCode(@NotNull Throwable exception){
var analyticsProviderException = findCause(AnalyticsProviderException.class,exception);
if (analyticsProviderException != null){
var connectionIssueCodes = List.of(503,504,502);
return connectionIssueCodes.contains(analyticsProviderException.getResponseCode());
}
return false;
}
private static boolean isConnectTimeout(@NotNull Throwable exception){
return SocketTimeoutException.class.equals(exception.getClass()) && "Connect timed out".equalsIgnoreCase(exception.getMessage());
}
private static boolean isIOExceptionTimeout(@NotNull Throwable exception) {
return IOException.class.equals(exception.getClass()) &&
exception.getMessage() != null &&
exception.getMessage().toLowerCase().contains("timeout");
}