Skip to content
Loading
how to get the message of SqlException error?
  • Thanks, but this is for a Console  App. My application is WSP. It doesn't work.
  • Kirtesh Shah
    Please see below example,
    1. public static void ShowSqlException(string connectionString)  
    2. {  
    3.     string queryString = "EXECUTE NonExistantStoredProcedure";  
    4.     StringBuilder errorMessages = new StringBuilder();  
    5.   
    6.     using (SqlConnection connection = new SqlConnection(connectionString))  
    7.     {  
    8.         SqlCommand command = new SqlCommand(queryString, connection);  
    9.         try  
    10.         {  
    11.             command.Connection.Open();  
    12.             command.ExecuteNonQuery();  
    13.         }  
    14.         catch (SqlException ex)  
    15.         {  
    16.             for (int i = 0; i < ex.Errors.Count; i++)  
    17.             {  
    18.                 errorMessages.Append("Index #" + i + "\n" +  
    19.                     "Message: " + ex.Errors[i].Message + "\n" +  
    20.                     "LineNumber: " + ex.Errors[i].LineNumber + "\n" +  
    21.                     "Source: " + ex.Errors[i].Source + "\n" +  
    22.                     "Procedure: " + ex.Errors[i].Procedure + "\n");  
    23.             }  
    24.             Console.WriteLine(errorMessages.ToString());  
    25.         }  
    26.     }  
    27. }