我怎样才能改善这种例外情况下重试? [英] How can I improve this exception retry scenario?

查看:219
本文介绍了我怎样才能改善这种例外情况下重试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web服务方法我打电话是第三方,我的域之外。出于某种原因,现在每一次Web服务失败,网关超时。其间歇性和一个失败的尝试能够成功后直接给它的调用。

I have a web service method I am calling which is 3rd party and outside of my domain. For some reason every now and again the web service fails with a gateway timeout. Its intermittent and a call to it directly after a failed attempt can succeed.

现在我离开了我一个编码的困境,我有一些代码应该做的伎俩,但代码看起来业余小​​时,你会看到下面。

Now I am left with a coding dilemma, I have code that should do the trick, but the code looks like amateur hour, as you'll see below.

这是非常糟糕的代码,还是可以接受给出的使用情况如何?如果其不能接受的,我怎么能提高呢?

Is this really bad code, or acceptable given the usage? If its not acceptable, how can I improve it?

请努力尝试到板着面孔,而在寻找它。

Please try hard to keep a straight face while looking at it.

try
{
    MDO = OperationsWebService.MessageDownload(MI);
}
catch
{
    try
    {
        MDO = OperationsWebService.MessageDownload(MI);
    }
    catch
    {
        try
        {
            MDO = OperationsWebService.MessageDownload(MI);
        }
        catch
        {
            try
            {
                MDO = OperationsWebService.MessageDownload(MI);
            }
            catch 
            {
                try
                {
                    MDO = OperationsWebService.MessageDownload(MI);
                }
                catch (Exception ex)
                {
                    // 5 retries, ok now log and deal with the error.
                }
            }
        }
    }
}


推荐答案

您可以做到在一个循环。

You can do it in a loop.

Exception firstEx = null;
for(int i=0; i<5; i++) 
{
    try
    {
        MDO = OperationsWebService.MessageDownload(MI);
        firstEx = null;
        break; 
    }
    catch(Exception ex)
    {
        if (firstEx == null) 
        {
            firstEx = ex;
        }
        Thread.Sleep(100 * (i + 1));
    }
}
if (firstEx != null) 
{
    throw new Exception("WebService call failed after 5 retries.", firstEx);
}

这篇关于我怎样才能改善这种例外情况下重试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆