Improve company productivity with a Business Account.Sign Up

x
?
Solved

How to catch SQL Errors from ADO.NET

Posted on 2016-10-03
3
Medium Priority
?
291 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:Ali Shah
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:Ali Shah
ID: 41826339
Thanks a lot. By adding throwerror it works.

regards
0

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

This shares a stored procedure to retrieve permissions for a given user on the current database or across all databases on a server.
Article by: Shaun
Tiling windows is a great way to see multiple applications at once. Windows Tiler is a tool that automatically tiles open application windows as the open and close.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

606 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