2

如果我对 try/catch 块中的错误的响应是将用户重定向到错误页面,那么 try/catch 块的行为就好像没有错误一样。如果我将其更改为执行其他操作,则代码可以正常工作。

例子:

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.
}

从另一篇文章中,我了解到 Response.Redirect() 方法存在布尔重载。我尝试了 true 和 false 并且 try/catch 块仍然表现得好像有错误一样。

这是怎么回事?

4

4 回答 4

10

当您进行 Response.Redirect 时,会引发 ThreadAbortException。因此,要获得您所描述的结果,您需要按如下方式修改您的代码:

try  
{
   // Do some cool stuff that might break
}
catch(ThreadAbortException)
{

}
catch(Exception e)
{
  // Catch other exceptions
  Response.Redirect("~/myErrorPage.aspx");
}
于 2012-09-10T19:58:40.297 回答
4
Response.Redirect("url");

按照设计,这将通过抛出异常来终止调用线程。

Response.Redirect("url", false);

将防止抛出异常,但将允许代码继续执行。

使用

Response.Redirect("url", false);
HttpContext.Current.ApplicationInstance.CompleteRequest();

将重定向用户并停止执行而不抛出异常。

于 2012-09-10T20:01:53.900 回答
1

您应该使用HandleError属性。

[HandleError]
public ActionResult Foo(){
    //...

    throw new Exception(); // or code that throws execptions

    //...
}

这样,异常会自动导致重定向到错误页面。

于 2012-09-10T19:58:33.853 回答
0

您忘记了引号和分号:

Response.Redirect("error.htm");
于 2012-09-10T19:58:28.590 回答