Nested try-catch with Reponse.Redirect in ASP.NET
I have nested try catch blocks
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=" + Serv开发者_如何学Cer.UrlEncode(ex.Message)
+ "&src=" + Server.UrlEncode(ex.StackTrace));
}
finally
{
conn.Close();
}
If a SqlExeception is caught at inner first catch block, then also because try...catch surrounds Response.Redirect
, the ThreadAbortException generated by the transfer is caught by the outer catch block.
How can I solve this problem? Thanks!
Read this article
What you can do most simply is not redirect inside your try/catch harnesses:
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
}
Consider changing the code in the first response
if ( url != "" ) { Response.Redirect(url);}
to
if (!string.IsNullOrEmpty(url)) { Response.Redirect(url);}
Use a variable to track when an error has been thrown in the inner try...catch and then check it in the second by surrounding the Response.Redirect with an if statement.
Whenever you use Response.Redirect inside a try-catch block, you should add the second parameter.
Instead of this:
Response.Redirect("somepage.aspx");
Do this:
Response.Redirect("somepage.aspx", false);
When that boolean is true, the page contents are sent to the new page (so you can use the form values). When that boolean is false, the page contents are not sent. This is probably what you want. You would know if you needed true.
Another approach to this is to catch the ThreadAbortException in an empty Catch block.
精彩评论