ASP.NET logic / connection path and error passing

I just downloaded my first ASP.NET (as part of my learning vb.net) and got into a terrible mess with connection pooling (funny things happen when there is more than one user of your website), all sorted now are better to use try catch statements (well, and the idea had to learn). BUT I was wondering if this is the best / final method, now if the attempt fails then a lot of details on the page are not placed / updated, so if you are doing any work with the database and the attempt fails, reload the page ... redirect to yourself and hope it works next time ... or just tell the user that an error has occurred and they should try again?

thank

0


source to share


3 answers


You must use operators' using

for all objects that implement IDisposable

(e.g. connections and readers). The 'using' statement is converted to a try-finally block under the covers and ensures that Dispose () is called even if an error occurs.

Here's a sample snippet:



using (SqlConnection conn = new SqlConnection(this.connectionString))
{
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "LoadFromRepository";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@ID", fileID);

        conn.Open();
        using (SqlDataReader rdr =
                   cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            while (rdr.Read())
            {
                // do something with read data
            }
        }
    }
}

      

0


source


I would never redirect automatically and hope it works next time (you might end up in an infinite loop).

Provide the user and, if necessary, a link to try again.



You can even parse your exception to see if another attempt helps. Some exceptions are indeed errors, and another attempt will not help.

0


source


If an unexpected error occurs, redirect the user to the error page as this will likely happen next time.

Have you studied the "Usage" instructions for DB connections and readers?

0


source







All Articles