Solved

How to catch SQL Errors from ADO.NET

Posted on 2016-10-03
3
119 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 12

Accepted Solution

by:
Nakul Vachhrajani earned 500 total points
ID: 41826131
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 28

Expert Comment

by:Pawan Kumar
ID: 41826156
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
ID: 41826339
Thanks a lot. By adding throwerror it works.

regards
0

Featured Post

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
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 set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

825 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