重试某些例外的方法

时间:2016-07-06 18:58:50

标签: java exception-handling

我有以下方法,它使用代理从服务器检索信息。有时由于代理不当,我会收到SocketExceptionSSLExceptionSSLHandshakeExceptionConnectException

正如您在我的方法中所看到的,我已经在使用catch (IOException ioe)我需要这样做,以便在服务器返回除代码200之外的任何内容时获取服务器响应的内容。

如果出现上述异常,如何重试方法?

public String getMeta() throws IOException
{

    HttpsURLConnection con = null;
    InputStream is = null;
    StringWriter writer = new StringWriter();
    try
    {
        String url = "https://api.myapp.com/meta";
        URL urlObj = new URL(url);

        if (useProxy && fullProxy)
        {
            myapp.Proxy proxyCustom = getRandomProxy();
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyCustom.getProxyIp(), proxyCustom.getProxyPort()));
            con = (HttpsURLConnection) urlObj.openConnection(proxy);
        }
        else
        {
            con = (HttpsURLConnection) urlObj.openConnection();
        }

        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        con.setRequestProperty("host", urlObj.getHost());
        con.setRequestProperty("Connection", "Keep-Alive");

        int responseCode = 0;

        responseCode = con.getResponseCode();

        is = con.getInputStream();
        writer = new StringWriter();
        IOUtils.copy(is, writer, "UTF-8");
    }
    catch (IOException ioe)
    {
        if (con instanceof HttpsURLConnection)
        {
            HttpsURLConnection httpConn = (HttpsURLConnection) con;
            int statusCode = httpConn.getResponseCode();
            if (statusCode != 200)
            {
                is = httpConn.getErrorStream();
                writer = new StringWriter();
                IOUtils.copy(is, writer, "UTF-8");
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return writer.toString();
}

2 个答案:

答案 0 :(得分:0)

我将采用的方法是创建一个新的重试方法,并在getMeta()方法结束时调用它,以便在出现异常时调用它 我假设您应该只调用几次重试,因此getMeta应该在一定次数之后抛出一些异常,如RetryException

public String getMeta() throws IOException, RetryException
{

    HttpsURLConnection con = null;
    InputStream is = null;
    StringWriter writer = new StringWriter();
    try
    {
        String url = "https://api.myapp.com/meta";
        URL urlObj = new URL(url);

        if (useProxy && fullProxy)
        {
            myapp.Proxy proxyCustom = getRandomProxy();
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyCustom.getProxyIp(), proxyCustom.getProxyPort()));
            con = (HttpsURLConnection) urlObj.openConnection(proxy);
        }
        else
        {
            con = (HttpsURLConnection) urlObj.openConnection();
        }

        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        con.setRequestProperty("host", urlObj.getHost());
        con.setRequestProperty("Connection", "Keep-Alive");

        int responseCode = 0;

        responseCode = con.getResponseCode();

        is = con.getInputStream();
        writer = new StringWriter();
        IOUtils.copy(is, writer, "UTF-8");

        return writer.toString();
    }
    catch (IOException ioe)
    {
        if (con instanceof HttpsURLConnection)
        {
            HttpsURLConnection httpConn = (HttpsURLConnection) con;
            int statusCode = httpConn.getResponseCode();
            if (statusCode != 200)
            {
                is = httpConn.getErrorStream();
                writer = new StringWriter();
                IOUtils.copy(is, writer, "UTF-8");

                return writer.toString();
            }
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return retryGetMeta();
}


private String retryGetMeta()
{
   try
   {
       return getMeta();
   }
   finally
   {
       //Do your stuff
   }
}

public RetryException extends Exception
{
    private   String message =  "Retries exceeded";

      public String getMessage()
      {
         return message;
      }

}

如果你的getMeta()中抛出异常,catch会像你现在那样做它的东西,但之后,将调用retryGetMeta

答案 1 :(得分:0)

  

如果出现上述异常,如何重试方法?

下面显示的一种方法是让getMeta方法实际抛出IOException。然后,由于任何捕获的异常,您可以使用caller方法递归调用自身。

  

我希望有一种简单的方法来设置它应该重试的次数

为了能够多次调用方法n,将次数作为参数传递,并相应地处理停止标准逻辑。例如:

public String caller(int total) throws IOException{
    return callerImpl(1, total);
}

public String callerImpl(int current, int total) throws IOException{
    try{
        return getMeta();
    }catch(IOException e){
        current++;
        if ( current > total ){
            throw e;//or return null or empty string, depending upon upstream requirements
        }
        return callerImpl(current, total);
    }

    return null;
}

在getMeta中:

try{
    ....
}catch(IOException io){
    //log or handle io
    throw io;
}

注意,上面没有涉及抛出异常的日志/逻辑,您可能希望以某种方式处理它们。