簡體   English   中英

在Try / Catch Block中使用Response.Redirect(url)

[英]Using Response.Redirect(url) in Try / Catch Block

如果我對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塊仍然表現得好像有錯誤。

這是怎么回事?

當你的Response.Redirect,拋出一個ThreadAbortException。 因此,要獲得您所描述的結果,您需要修改代碼,如下所示:

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

}
catch(Exception e)
{
  // Catch other exceptions
  Response.Redirect("~/myErrorPage.aspx");
}
Response.Redirect("url");

通過設計,這將通過拋出異常來終止調用線程。

Response.Redirect("url", false);

將阻止拋出異常,但是會允許代碼繼續執行。

運用

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

將重定向用戶並停止執行而不拋出異常。

您應該使用HandleError屬性。

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

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

    //...
}

這樣,異常會自動導致重定向到錯誤頁面。

你忘了引號和分號:

Response.Redirect("error.htm");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM