How do I throw (and catch) an exception from my DAL to my presentation layer?

How do I throw an exception (my cmd.ExecuteNonQuery command is bombing), from my DAL to my presentation layer so that I can display what the actual error message is?
LVL 1
Michael SterlingWeb Applications DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

louisfrCommented:
What currently happens? Are you catching the exception somewhere? Or does your program crash?
Lokesh B RDeveloperCommented:
Hi,

Add the try catch in the presentation layer and show the error message in Label.

Sample code here

In DAL

 public int SaveEmployee(string firstName, string lastName)
            {
                try
                {
                    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
                    {
                        SqlCommand cmd = new SqlCommand("INSERT INTO Employee(FirstName,LastName) VALUES (@FirstName, @LastName);", con);
                        cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = firstName;
                        cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = lastName;

                        con.Open();
                        return cmd.ExecuteNonQuery();
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }

Open in new window


In Presentation Layer on Button Click

   
protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                CustomerHelper helper = new CustomerHelper();
                int result = helper.SaveEmployee("Scott", "Gu");

                if (result > 0)
                 {
                    Label1.Text = "Employee added successfully.";
                 }
            }
            catch (Exception ex)
            {
                Label1.Text = ex.Message;
            }
        }

Open in new window

Jacques Bourgeois (James Burger)PresidentCommented:
Although Lokesh code does answer your basic question, the following is usually a better idea.

Do the following on your call for the ExecuteQuery, and also trap SqlException in your presentation layer.

			try
			{
				// Your code
			}
			catch (SqlException)
			{
				throw;
			}

Open in new window


This assumes that you get an SqlException. Otherwise, simply catch Exception. The SqlException is more interesting because it offers you a lot more than just the Message. It has properties that give you more information such as the SQL Server error code (you can look it up to get more details than just the message), the stored procedure if you have used one, etc.

These informations will be available in the presentation layer and could be used to build a more elaborate error message then simply ex.Message. They are also very useful when debugging.

It also solves an inconvenient with throw new Exception(ex.Message). New resets the StackTrace, so you lose the trace of the calls that led to your error, an information that is sometimes essential to understand a problem. Throw simply relay the same object so no information is lost.

Even if it is not important to get all these extra informations in your current situation, it could be if you call you method from somewhere else or from another application. When you develop a DAL, you should try to make it ready for different situations, and this is one way to do it.
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

balderCommented:
There is no point in catching an re-throwing an exception unless you do any handling of the exception in your catch.

Moving the exception message to a new exception is completely unecessary.


You have to implement an error handling logic, do you intend to present every fault to the end user, or will you just inform the user that there was an DB error?

In the first case you just catch the exception in the presentation layer and show Exception.Message to the user.
In the second case you catch the exception in the DAL, log Exception.Message and Exception.Stacktrace. Create an new Exception with the Message, "A DB error occured". Then you catch this exception in the presentation layer.
Michael SterlingWeb Applications DeveloperAuthor Commented:
@balder: currently I am attempting to see the DB error. For some reason, with the database that I'm using, there isn't an easy way to see the actual error that is being thrown,. so how do I do the second method!  (example code) how do I log the exception message, and stack trace? (example code)  this probably won't make it into the production version, I am using it to help me solve a problem, that I'm having right now, that is not easily solved through normal debugging.
balderCommented:
Exception class - her are the StackTrace and Message properties on the Exception class explained, they are both strings.

For logging you could either use a logging package like NLog, og just push it out to a file with AppendAllText

But since you are not planning for a production release of this I would have used the debugger to catch the exception and investigate the exception message.
käµfm³d 👽Commented:
@balder
There is no point in catching an re-throwing an exception...
I disagree. At times--mind you not every time--it can help make clear that you--the original developer--understood that an exception was being raised, but you that you were deferring to another layer to actually handle the error. I do this sometimes in my service layers when one service method calls another service method. My catch usually deals with logging, and there's no point in logging the same error twice!
balderCommented:
@käµfm³d - why did you exclude the "unless ..." part of that citation?

And, when you catch an exception for error logging, I assume you throw a new exception (or swallow it), not re-throw the caught exception?
When I do this sort of thing I normally place the original exception as an inner exception in the new one.
käµfm³d 👽Commented:
why did you exclude the "unless ..." part of that citation?
Because it is not applicable to my assertion.

And, when you catch an exception for error logging, I assume you throw a new exception (or swallow it), not re-throw the caught exception?
My pattern as of late is to catch exceptions at the outer-most level of my service layer. I log the error there. I then return null to the UI layer as a signal that something went wrong. Keep in mind that currently I work mainly on web services, so there is not much I need to "display" to the user in terms of something going wrong. Usually I send back a 500 - Internal Server Error because there's not anything the client could do to fix the request at that point.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Michael SterlingWeb Applications DeveloperAuthor Commented:
Thank you for all the input and information, it will all definitely be useful as I move forward on this project. I just split the points as I think they were all valuable. To "purge my conscience" I must say that what the solution actually was came to me in an indirect way. From the start, I knew that at the root, what ever was causing this, had to do with the fact that I was using a newer version of an IBM.DB2.Data.iSeries .dll. The problem was that the code/application was either shutting down or throwing some really crazy, (my personal opinion) java script error, from a file named: 'ScriptResources.axd', that, for me, was completely "unrelated" as far as I could tell (see the included image). So after researching enough links (some related and some not as related), I stumbled upon this one:

http://forums.asp.net/t/2007349.aspx?Error+in+ScriptResource+axd+Sys+WebForms+PageRequestManagerServerErrorException+The+IListSource+does+not+contain+any+data+sources+
About half of the way down there is a “Reply” in a green header, within the reply is this:

“I found my problem, I had altered the schema name in the database during the project and failed to update an SQL query in the project.  While the schema was still valid in the development environment it was not in the hosted server environment.  The error was pointing me in the right direction, but my first assumption that it was a compatibility issue with the ajax Control Toolkit, was incorrect.”

It got me to thinking that maybe, the new .dll doesn’t deal with datatypes as loosely / freely as the old one. So I stripped away all but one field in the update statement that was blowing up and low and behold, the update (the ExecuteNonQuery) statement worked! So now I am methodically going through the fields to determine which one is blowing it up. This is kind of a "brute force" approach but thorough, and besides I still don't know if, what ever error message, I would eventually be able to see using the techniques described above, the message would help me if it didn't say: "There is a datatype mismatch" or something similar. And even if it did, I don't know that it would tell me which field. So I still think I'd wind up right where I'm at. I don't know? Thanks again for the input and ideas!

Java Script Error
Michael SterlingWeb Applications DeveloperAuthor Commented:
Thank you all!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.