Solved

How to catch SQL Errors from ADO.NET

Posted on 2016-10-03
3
172 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 14

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 29

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

Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

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…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
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.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

615 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