When to log errors in ASPX when using database connections? In the following code, the authors of Pro ASP.NET 3.5 in C# 2008 (Third ed), suggest logging an SQL error in the catch block. My questions are:
Is this common practice?
Is this the best practice?
In short, would it be better to close the current connection and handle the error completely separately? What are the advantages and disadvantages for either approach?
Edited to add: To clarify the question is not IF one should log (that question is already discussed elsewhere), this question is more specific. The question is where in the code to log. Should it be done in the catch (while the connection is still open) or should the current connection be close and logging completely separate? Not the section to add logging as part of the catch (even if it calls an outside method, that connection remains open) until it returns and reaches the 'finally'.
public int InsertEmployee(EmployeeDetails emp)
{
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("InsertEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 10));
cmd.Parameters["@FirstName"].Value = emp.FirstName;
cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 20));
cmd.Parameters["@LastName"].Value = emp.LastName;
cmd.Parameters.Add(new SqlParameter("@TitleOfCourtesy", SqlDbType.NVarChar, 25));
cmd.Parameters["@TitleOfCourtesy"].Value = emp.TitleOfCourtesy;
cmd.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 4));
cmd.Parameters["@EmployeeID"].Direction = ParameterDirection.Output;
try
{
con.Open();
cmd.ExecuteNonQuery();
return (int)cmd.Parameters["@EmployeeID"].Value;
}
catch (SqlException err)
{
// Replace the error with something less specific.
// You could also log the error now.
throw new ApplicationException("Data error.");
}
finally
{
con.Close();
}
}