【问题标题】:Nested try-catch with Reponse.Redirect in ASP.NET在 ASP.NET 中使用 Response.Redirect 嵌套 try-catch
【发布时间】:2012-02-04 00:11:54
【问题描述】:

我已经嵌套了 try catch 块

try
{
    // statements
    try
    {
        // statements
    }
    catch(SqlException sqlex)
    {
        Response.Redirect(@"~/Error.aspx?err=" + Server.UrlEncode(sqlex.Message)
                              + "&src=" + Server.UrlEncode(sqlex.ToString()));
    }
    catch (Exception ex)
    {
        Response.Redirect(@"~/Error.aspx?err=" + Server.UrlEncode(ex.Message)
                              + "&src=" + Server.UrlEncode(ex.ToString()));
    }
    finally
    {
        conn.Close();
    }
}
catch (Exception ex)
{
    Response.Redirect(@"~/Error.aspx?err=" + Server.UrlEncode(ex.Message)
                          + "&src=" + Server.UrlEncode(ex.StackTrace)); 
}
finally
{
    conn.Close();
}

如果在内部第一个catch块捕获了SqlException,那么也因为try...catch包围Response.Redirect,传输产生的ThreadAbortException被外部catch块捕获。

我该如何解决这个问题?谢谢!

【问题讨论】:

  • 为什么需要嵌套try catch?

标签: c# asp.net nested try-catch


【解决方案1】:

阅读this article

你可以做的最简单的就是不在你的 try/catch 工具中重定向:

string url ;
try 
     { 
            // statements 
            try 
            { 
            } 
            catch(SqlException sqlex) 
            { 
               url = @"~/Error.aspx?err=" + Server.UrlEncode(sqlex.Message) + "&src=" + Server.UrlEncode(sqlex.ToString()); 
            } 
            catch (Exception ex) 
            { 
                url = @"~/Error.aspx?err=" + Server.UrlEncode(ex.Message) + "&src=" + Server.UrlEncode(ex.ToString()); 
            } 
            finally 
            { 
                conn.Close(); 
            } 
    } 
    catch (Exception ex) 
        { 
            url = @"~/Error.aspx?err=" + Server.UrlEncode(ex.Message) + "&src=" + Server.UrlEncode(ex.StackTrace);  
        } 
        finally 
        { 
            conn.Close(); 
        } 
} 

if ( url != "" ) {
    Response.Redirect(url);
}
else {
    // Page logic can continue
}

【讨论】:

    【解决方案2】:

    考虑更改第一个响应中的代码

    if ( url != "" ) { Response.Redirect(url);}
    

    if (!string.IsNullOrEmpty(url)) { Response.Redirect(url);}
    

    【讨论】:

      【解决方案3】:

      使用变量来跟踪内部 try...catch 何时引发错误,然后在第二个中通过使用 if 语句包围 Response.Redirect 来检查它。

      【讨论】:

        【解决方案4】:

        当你在 try-catch 块中使用 Response.Redirect 时,你应该添加第二个参数。

        而不是这个:

        Response.Redirect("somepage.aspx");
        

        这样做:

        Response.Redirect("somepage.aspx", false);
        

        当该布尔值为真时,页面内容将发送到新页面(因此您可以使用表单值)。 当该布尔值为 false 时,不会发送页面内容。这可能就是你想要的。你会知道你是否需要 true。

        另一种方法是在一个空的 Catch 块中捕获 ThreadAbortException。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-02-25
          • 2019-11-12
          • 2023-03-19
          • 1970-01-01
          • 2016-08-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多