Exceptions, and how best to retry when a connection is reset?(异常,以及在连接重置时如何最好地重试?)
问题描述
我有一些代码连接到 URL 以下载文件,然后对其执行一些处理.但是,有时我会收到错误 java.net.SocketException: Connection reset
.
I have some code which connects to a URL to download a file, and then performs some processing on it. However, sometimes I am receiving the error java.net.SocketException: Connection reset
.
当我收到此错误时,我想重试下载文件,最多说 3 次,然后再放弃.我想知道构建它的最佳方法是什么.
I would like to retry to download the file when I receive this error, say a maximum of 3 times before giving up on it. I would like to know what would be the best way to structure this.
以下是否正常.将 try-catch
块放在 while
循环内似乎可以接受,还是有更好的方法?
Does the following look ok. Does it seem acceptable to place the try-catch
block inside of a while
loop, or is there a better approach?
非常感谢所有帮助!
while(!connected && retries > 0) {
retries--;
URL downloadUrl;
URLConnection conn;
try {
downloadUrl = new URL(url);
conn = downloadUrl.openConnection();
conn.connect();
connected = true;
// Perform processing on downloaded file here
} catch (IOException e) {
Logger.batchLog(e);
}
}
推荐答案
我一直认为吞下异常总是不好的,但我认为,这是判断连接是否确实重置的唯一方法.我猜您正在根据您的要求处理异常,这就是所有问题.
I've been wired to think that swallowing an exception is always bad, but I think here, that's the only way to tell if the connection was indeed reset. I guess you are handling the exception according to your requirements, so that's all the matters.
但是,我会这样做,以免您吞下最后一个例外.如果它失败了 3 次,您将需要重新抛出该异常或以某种方式优雅地失败.
But I would, however, make it so you don't swallow the last exception. If it fails three times, you'll want to rethrow that exception or fail gracefully somehow.
这篇关于异常,以及在连接重置时如何最好地重试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:异常,以及在连接重置时如何最好地重试?
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01