Solved

How to catch SQL Errors from ADO.NET

Posted on 2016-10-03
3
98 Views
Last Modified: 2016-10-03
Hi guys,

I have got a stored procedure which has got the following error output parameters

@ErrorNumber = ERROR_NUMBER() ,
                    @ErrorSeverity = ERROR_SEVERITY() ,
                    @ErrorState = ERROR_STATE() ,
                    @ErrorProcedure = ERROR_PROCEDURE() ,
                    @ErrorLine = ERROR_LINE() ,
                    @ErrorMessage = ERROR_MESSAGE();

Open in new window


When i execute stored procedure from SQL Server i do get these error outputs as expected.
How do i catch these errors using ADO.Net?

My ADO.Net code is as followes

string connStr = "Server =(local); initial Catalog =Spaces;  integrated Security = SSPI";

        public void StoredProcedure(AddressesDto Dto)
        {





            using (SqlConnection cnSql = new SqlConnection(connStr))
            {

                SqlParameter errorNumber = new SqlParameter("@ErrorNumber", SqlDbType.Int)
                {
                    Direction = ParameterDirection.Output
                };
                SqlParameter errorSeverity = new SqlParameter("@ErrorSeverity", SqlDbType.Int)
                {
                    Direction = ParameterDirection.Output
                };
                SqlParameter errorState = new SqlParameter("@ErrorState", SqlDbType.Int)
                {
                    Direction = ParameterDirection.Output
                };
                SqlParameter errorProcedure = new SqlParameter("@ErrorProcedure", SqlDbType.NVarChar, 128)
                {
                    Direction = ParameterDirection.Output
                };
                SqlParameter errorLine = new SqlParameter("@ErrorLine", SqlDbType.Int)
                {
                    Direction = ParameterDirection.Output
                };
                SqlParameter errorMessage = new SqlParameter("@ErrorMessage", SqlDbType.NVarChar, 4000)
                {
                    Direction = ParameterDirection.Output
                };
                SqlParameter insertedLocations = new SqlParameter("@NumberOfInsertedLocations", SqlDbType.Int)
                {
                    Direction = ParameterDirection.Output
                };

                StringBuilder errorMessages = new StringBuilder();

                string message;

                cnSql.Open();

                SqlCommand cmSql = new SqlCommand("[CrossContext].[USP_Locations_AddPointLocations]", cnSql);
                cmSql.CommandType = CommandType.StoredProcedure;

                try
                {
                    cmSql.Parameters.Add(new SqlParameter("@LocationGuid", Dto.Guid));
                    cmSql.Parameters.Add(new SqlParameter("@AddressStringId", Dto.AddressStringId));
                    cmSql.Parameters.Add(new SqlParameter("@LocationName", Dto.LocationName));
                    cmSql.Parameters.Add(new SqlParameter("@AddressLine1", Dto.AddressLine1));
                    cmSql.Parameters.Add(new SqlParameter("@AddressLine2", Dto.AddressLine2));
                    cmSql.Parameters.Add(new SqlParameter("@AddressLine3", Dto.AddressLine3));
                    cmSql.Parameters.Add(new SqlParameter("@BuildingNumbers", Dto.BuildingNumber));
                    cmSql.Parameters.Add(new SqlParameter("@BuildingName", Dto.BuildingName));
                    cmSql.Parameters.Add(new SqlParameter("@Street", Dto.Street));
                    cmSql.Parameters.Add(new SqlParameter("@Locality", Dto.Locality));
                    cmSql.Parameters.Add(new SqlParameter("@Municipality", Dto.Municipality));
                    cmSql.Parameters.Add(new SqlParameter("@AdministrativeArea", Dto.AdministrativeArea));
                    cmSql.Parameters.Add(new SqlParameter("@SubAdministrativeArea", Dto.SubAdministrativeArea));
                    cmSql.Parameters.Add(new SqlParameter("@PostalCode", Dto.PostCode));
                    cmSql.Parameters.Add(new SqlParameter("@Iso3166MinusOneCountryAlpha2Code", Dto.Iso3166MinusOneCountryAlpha2Code));
                    cmSql.Parameters.Add(new SqlParameter("@Wgs84Longitude", Dto.Longitude));
                    cmSql.Parameters.Add(new SqlParameter("@Wgs84Latitude", Dto.Latitude));
                    cmSql.Parameters.Add(new SqlParameter("@PointBufferDistanceInMeters", Dto.PointBufferDistanceInMeters));
                    cmSql.Parameters.Add(new SqlParameter("@UniqueHashString", Dto.UniqueHashString));
                    cmSql.Parameters.Add(new SqlParameter("@SearchString", Dto.SearchString));
                    cmSql.Parameters.Add(errorNumber);
                    cmSql.Parameters.Add(errorSeverity);
                    cmSql.Parameters.Add(errorState);
                    cmSql.Parameters.Add(errorProcedure);
                    cmSql.Parameters.Add(errorLine);
                    cmSql.Parameters.Add(errorMessage);
                    cmSql.Parameters.Add(insertedLocations);



                    //cmSql.ExecuteScalar();

                    cmSql.ExecuteNonQuery();



                    //int erNumber =Convert.ToInt32(errorNumber.Value ?? 0);
                    //string errMsg = errorMessage.Value.ToString() ?? "No Error";

                    cnSql.Close();

                }
                catch (SqlException ex)
                {

                    for (int i = 0; i < ex.Errors.Count; i++)
                    {
                        errorMessages.Append("Index #" + i + "\n" +
                            "Message: " + ex.Errors[i].Message + "\n" +
                            "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                            "Source: " + ex.Errors[i].Source + "\n" +
                            "Procedure: " + ex.Errors[i].Procedure + "\n");
                    }

                    message = ex.ToString();
                }

    
           
            }
            

        }

Open in new window


When i debug this code i get no error and compiler doesn't go on catch block. However i know that there is an error and i get it when execute the stored procedure on SQL Server

Please note i am executing this ADo.Net code from SSIS so i can't use Entity Framework or Dapper within SSIS

regards
0
Comment
Question by:shah36
3 Comments
 
LVL 11

Accepted Solution

by:
Nakul Vachhrajani earned 500 total points
Comment Utility
There are 2 reasons why you don't hit the CATCH block in your ADO.net

1) No exception is being returned by the stored procedure called by the code. An exception happens in your T-SQL code and the stored procedure handles it. So, one option would be to use RAISEERROR to make the calling code "aware" that an exception was encountered (you can use THROW if you are using SQL 2012 and above)
To understand how THROW works, you can refer my blog post: https://nakulvachhrajani.com/2011/02/28/sunset-for-raiserror-and-sunrise-for-throw-sql-11-denali/)

2) You are using ExecuteNonQuery(), which means ADO.net is not expecting anything to be returned. Your error information (collected in the @Error* variables in the SP) is probably being returned as a data-set. You need to use a datareader to read the result returned by the stored procedure
0
 
LVL 17

Expert Comment

by:Pawan Kumar Khowal
Comment Utility
Try this..

Execute the stored procedure separately IN SSMS with the same parameters that you are doing from SSIS.
0
 

Author Closing Comment

by:shah36
Comment Utility
Thanks a lot. By adding throwerror it works.

regards
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now