异常,以及在连接重置时如何最好地重试?

2022-01-24 00:00:00 connection exception-handling java

我有一些代码连接到 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.

相关文章