2013-09-25 36 views
2

我有以下代碼調用存儲過程。我希望能夠捕獲運行存儲過程期間發生的任何錯誤。如何從Ado.net中捕獲SQL Server錯誤

try { 
      using (var connection = GetConnection()) { 

       using (SqlCommand cmd = connection.CreateCommand()) { 
        connection.Open(); 
        cmd.CommandType = CommandType.StoredProcedure; 
        cmd.CommandText = "VerifyInitialization"; 
        cmd.Parameters.Add(new SqlParameter("@userId", user.Id)); 
        cmd.Parameters.Add(new SqlParameter("@domainId", user.DomainId)); 
        cmd.ExecuteNonQueryAsync(); 
       } 

      } 
     } 
     catch (Exception ex) { 
      throw new LoginException(LoginExceptionType.Other, ex.Message); 
     } 

這是存儲過程,它基本上只是調用其他存儲過程。

ALTER PROCEDURE [dbo].[VerifyInitialization] 
-- Add the parameters for the stored procedure here 
@userId int, 
@domainId int 
AS 
BEGIN 
Begin Try 
SET NOCOUNT ON; 
Exec VerifyInitializationOfDefaultLocalizationItems 
Exec VerifyInitializationOfLayoutLists @domainId 
Exec VerifyInitializationOfLayoutListItems @domainId 
Exec VerifyInitializationOfLocalizationItems @domainId 
Exec VerifyInitializationOfLookupLists @domainId 
Exec VerifyInitializationOfLookupListItems @domainId 
End try 

Begin Catch 
    -- Raise an error with the details of the exception 
    DECLARE 
    @ErrMsg nvarchar(4000) = Error_message(), 
    @ErrSeverity int = ERROR_SEVERITY(); 

    RAISERROR(@ErrMsg, @ErrSeverity, 1) 
End Catch 
End 

我需要做什麼來捕捉存儲過程中將返回到C#中的錯誤?說例如一個字段名稱被重新命名,以防止其中一個存儲的過程運行。我不希望它失敗地失敗。

格雷格

+0

我沒有找到這個鏈接,它顯示了捕獲Sql Server錯誤的VB示例,但到目前爲止,我仍然無法捕捉到實際的異常。 http://support.microsoft.com/kb/321903/en-us –

+1

將ExecuteNonQueryAsync更改爲ExecuteNonQuery,或研究任務異步模式的工作方式。 – usr

+0

謝謝@usr,這是問題。 –

回答

2

使用ExecuteNonQueryAsync()你的情況,不如使用ExecuteNonQuery()一樣好。

try { 
    using (var connection = GetConnection()) { 
     using (SqlCommand cmd = connection.CreateCommand()) { 
     connection.Open(); 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.CommandText = "VerifyInitialization"; 
     cmd.Parameters.Add(new SqlParameter("@userId", user.Id)); 
     cmd.Parameters.Add(new SqlParameter("@domainId", user.DomainId)); 
     //cmd.ExecuteNonQueryAsync(); - This line should be .ExecuteNonQuery() 
     cmd.ExecuteNonQueryAsync(); 
     } 
    } 
} 

catch (Exception ex) { 
    throw new LoginException(LoginExceptionType.Other, ex.Message); 
} 

你可能要考慮的是趕上一個更具體的SqlException,而不是更一般的Exception,類似這樣的還有一件事:

catch (SqlException exc) { 
    throw new SqlException(/* Handle your exception messaging here. */); 
} 

catch (Exception ex) { 
    throw new LoginException(LoginExceptionType.Other, ex.Message); 
} 

編輯:我張貼了這個答案沒有意識到@ usr已經在上面的評論中回答了它。我會刪除,如果你喜歡。

+0

這是一個很好的解釋,我將標記爲答案,因爲我不能將評論標記爲答案。 –

+0

謝謝Greg,我明白了! – Brian