[英]Using Response.Redirect(url) in Try / Catch Block
If my response to errors in a try/catch block is to redirect users to an error page, the try/catch block behaves as if there was an error when there was not. 如果我对try / catch块中的错误的响应是将用户重定向到错误页面,则try / catch块的行为就像没有时出现错误一样。 If I change it to do something else, the code works fine. 如果我改变它做其他事情,代码工作正常。
Example: 例:
try
{
//do this SQL server stuff
}
catch
{
Response.Redirect(error.htm)
//Change this to lblErr.Text = "SQL ERROR"; and the code in try works fine.
}
From another post I learned there was a boolean overload to the Response.Redirect() method. 从另一篇文章我了解到,Response.Redirect()方法有一个布尔重载。 I tried both true and false and the try/catch block still behaved as if there were an error. 我尝试了true和false,并且try / catch块仍然表现得好像有错误。
What's the deal? 这是怎么回事?
When you Response.Redirect, that throws a ThreadAbortException. 当你的Response.Redirect,抛出一个ThreadAbortException。 So to get the outcome you are describing you'll want to mod your code as follows: 因此,要获得您所描述的结果,您需要修改代码,如下所示:
try
{
// Do some cool stuff that might break
}
catch(ThreadAbortException)
{
}
catch(Exception e)
{
// Catch other exceptions
Response.Redirect("~/myErrorPage.aspx");
}
Response.Redirect("url");
By design this will terminate the calling thread by throwing an exception. 通过设计,这将通过抛出异常来终止调用线程。
Response.Redirect("url", false);
Will prevent the exception from being thrown, however will allow the code to continue executing. 将阻止抛出异常,但是会允许代码继续执行。
Using 运用
Response.Redirect("url", false);
HttpContext.Current.ApplicationInstance.CompleteRequest();
Will redirect the user and stop execution without throwing an exception. 将重定向用户并停止执行而不抛出异常。
You should use the HandleError attribute. 您应该使用HandleError属性。
[HandleError]
public ActionResult Foo(){
//...
throw new Exception(); // or code that throws execptions
//...
}
That way exceptions automatically cause redirection to an error page. 这样,异常会自动导致重定向到错误页面。
你忘了引号和分号:
Response.Redirect("error.htm");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.