2011-02-11 157 views
2

有沒有辦法捕捉數據庫異常,然後重定向到錯誤頁面?我有一個數據訪問類,我用它來建立一個sql連接,然後調用它來執行我的SQL命令。我的問題是,如果我的數據庫不可用,我不能捕獲該錯誤。這裏是我用我的類代碼:捕獲數據庫連接錯誤

Protected Function GetConnection() As SqlConnection 
    Dim ret_conn As SqlConnection 
    ret_conn = New SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings("EUCNET00617").ToString()) 
    ret_conn.Open() 
    GetConnection = ret_conn 
End Function 
+2

你有沒有讀到「在try..catch」塊?!? http://msdn.microsoft.com/en-us/library/fk6t46tz%28v=VS.90%29.aspx – BertuPG 2011-02-11 12:58:29

回答

1

什麼你要找的是try/catch/finally結構。這允許您捕獲異常(錯誤)並對其做出反應。現在

Protected Function GetConnection() As SqlConnection 
    Dim ret_conn As SqlConnection 
    Try 
     ret_conn = New SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings("EUCNET00617").ToString()) 
     ret_conn.Open() 
     GetConnection = ret_conn 
    Catch exceptionThatICaught as System.Exception 
     ' You could also perform logging of details from exceptionThatICaught here 
     GetConnection = Null 
    End Try 
End Function 

,你GetConnection函數將返回Null當它是無法創建並打開一個連接,這意味着調用代碼,它可以反應到連接返回被空,而不是崩潰。

您可能已經注意到,我把在Catch塊中的例外是System.Exception,通常趕上這樣的通用(所有異常是從System.Exception派生)會被認爲是不好的形式,因爲它意味着你要照顧任何東西發生時不知道發生了什麼。這只是一個例子給你看雖然=)

它總是值得檢討你包裝一下你試試功能的MSDN文檔頁/左右趕上像他們有些人名單「預期」的(但不是所有)如果您有處理該失敗案例的方法,則可能會拋出的異常可以被認爲是catch。在這種情況下,要查看的頁面將是:

SqlConnection.Open列出兩個例外,它可以拋出,InvalidOperationExceptionSqlException的文檔。我強烈建議您查看該文檔,以便決定「做什麼」和「捕獲」哪種異常類型,您認爲適合您這樣做。

0

使用try/catch塊(MSDN Link

Protected Function GetConnection() As SqlConnection 
    Try 
     Dim ret_conn As SqlConnection 
     ret_conn = New SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings("EUCNET00617").ToString()) 
     ret_conn.Open() 
     GetConnection = ret_conn 
    Catch Ex As Exception 
     'Write code to log error and then redirect to your error page 
    Finally 
     'Something you always want to happen 
    End Try 
End Function 
0

在閱讀代碼時首先想到的是,如果在打開連接時出現錯誤,SqlConnection.Open會拋出SqlClientException異常。可以通過將ASP.NET重定向到錯誤頁面來捕獲此異常並對其做出響應。

Try 

    ret_con.Open(); 

Catch Exception ex As SqlClientException 

    //logging and other things ommitted 
    Response.Redirect("/errors/page"); 
    End Try 

一本特定解決方案的negitives的是,它使你的數據訪問類,以便了解有關HttpResponse對象這取決於你是多麼重要關注點分離是無法令人接受。

另一個選項是捕獲異常,記錄並重新拋出異常,以便它可以冒泡,導致重定向到通過web.config爲該站點配置的自定義錯誤頁面。有關設置自定義錯誤的更多信息,請參見here

Appoligies爲可能無效的VB,這不是我的母語,我怕