?
Solved

How to catch SQL Errors from ADO.NET

Posted on 2016-10-03
3
Medium Priority
?
243 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 14

Accepted Solution

by:
Nakul Vachhrajani earned 2000 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 38

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

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

Question has a verified solution.

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

An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Ready to get certified? Check out some courses that help you prepare for third-party exams.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
SQL Database Recovery Software repairs the MDF & NDF Files, corrupted due to hardware related issues or software related errors. Provides preview of recovered database objects and allows saving in either MSSQL, CSV, HTML or XLS format. Ensures recov…
Suggested Courses

621 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