C# ASP.NET中带有Reponse.Redirect的嵌套try-catch
我有嵌套的try-catch块C# ASP.NET中带有Reponse.Redirect的嵌套try-catch,c#,asp.net,nested,try-catch,C#,Asp.net,Nested,Try Catch,我有嵌套的try-catch块 try { // statements try { // statements } catch(SqlException sqlex) { Response.Redirect(@"~/Error.aspx?err=" + Server.UrlEncode(sqlex.Message) + "&src=" + Serve
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块捕获到SqlExeception,那么也因为try…catch包围了Response.Redirect
,由传输生成的ThreadAbortException被外部catch块捕获
我怎样才能解决这个问题?谢谢 使用变量跟踪内部try…catch中何时抛出错误,然后在第二个中围绕响应进行检查。使用if语句重定向。无论何时使用Response。在try-catch块中重定向,都应添加第二个参数 与此相反:
Response.Redirect("somepage.aspx");
这样做:
Response.Redirect("somepage.aspx", false);
当该布尔值为true时,页面内容将发送到新页面(因此您可以使用表单值)。
如果该布尔值为false,则不发送页面内容。这可能是你想要的。你会知道你是否需要真的
另一种方法是在空的catch块中捕获ThreadAbortException。Read
您可以做的最简单的事情不是在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
}
考虑更改第一个响应中的代码
if ( url != "" ) { Response.Redirect(url);}
到
为什么需要嵌套的try-catch?
if (!string.IsNullOrEmpty(url)) { Response.Redirect(url);}