how to handle error in Class

Jagjit Saini 106 Reputation points
2021-07-10T16:17:55.337+00:00

Hi

I have below Class & want if there is any error , then it should be logged in Database and Error message should get displayed to user.

public class LocationDb
{
int i;
string output = string.Empty;
public List<Location> GetAllLocation()
{
List<Location> objLocation = new List<Location>();
using (SqlConnection con = new SqlConnection(Common.Con))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_Location1", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@朱大星 ", "R");
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
objLocation.Add(new Location
{
Id = rdr["Id"].ToString(),
Description = rdr["Description"].ToString(),
IsActive = Convert.ToBoolean(rdr["IsActive"]),
});
}
}
}
Thanks

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,490 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Michael Taylor 54,401 Reputation points
    2021-07-10T16:33:35.997+00:00

    While you could handle the error here that is probably not the best choice. The issue is that you'll likely have many places in code where you want to log errors. In general unless you intend to actually handle the error then you shouldn't be using exception handling inside individual methods. This is especially true if you need to "report it" to the user as most classes (this one included) are too low level to do that.

    Since you tagged this as MVC I assume you want to report this to the view that your user is going to see. Therefore it needs to be handled in the controller action that is called.

       public class MyController : Controller  
       {  
          public ActionResult MyAction ()  
          {  
             try  
             {  
                 DoWork();  
                 return View();  
             } catch (Exception e)  
             {  
                 ReportError(e);  //Your helper method to log the error  
                 return View("Error");   //Your error view you want to show or however you "report" errors in the UI  
             };  
          }  
       }  
    

    But as mentioned earlier this becomes tedious as you add more controller actions. Therefore the preferred approach in MVC is to create an exception filter as fully documented here. In this approach you create a custom exception filter that does the generic error handling logic (logging in this case). Then let the exception flow on. Register the filter globally at app startup, in most cases. MVC is already configured to automatically show your error page on an unhandled exception so you don't need to do anything else. If you don't want that then you'll need to customize how errors are returned on a per-action basis. But going this route makes it harder for your actions to know when something has failed. Refer to the docs linked earlier for a complete example of how to do this.

    For the exception filter itself logging is very common. In fact unless you have rolled your own then if you're using a third party logging system like Log4Net or NLog then they already have providers that can do this. You just add the appropriate logger (however that works for the system you're using) and you're done. If you did roll your own then in the exception filter simply open the DB connection and write to your error log.

       public class LogErrorsExceptionFilterAttribute : ExceptionFilterAttribute  
       {  
          public override void OnException ( HttpActionExecutedContext context )  
          {  
             //TODO: Should probably ignore common exceptions that aren't log worthy such as 401s, 404s, etc  
         
             //Log it  
             using (var conn = new SqlConnection(...))  
             {  
                var cmd = new SqlCommand("your query to insert a log entry", conn);  
                //Set parameters here...  
         
                conn.Open();  
                cmd.ExecuteNonquery();  
             };  
          }  
       }  
    

    Note that exception filters must be error resilient. If the filter fails while trying to handle an exception you lose the original exception therefore be very careful what you do. For example in the above you are connecting to a DB but if the DB is unavailable (and that is the error) then your logger will fail as well. Make sure your filter doesn't cause its own exceptions. Additionally this will be potentially slow in error cases so consider logging async instead which is outside the scope of this question.

    0 comments No comments

  2. Yijing Sun-MSFT 7,081 Reputation points
    2021-07-12T07:58:35.597+00:00

    Hi @Jagjit Saini ,
    As far as I think,there are two ways to show the error message:

    1. Using error page, the current page will not display, it will redirect to the error page. Such as you could redirect to error page in the Application_Error event.
    2. Using try catch statement to get the exception message, then display it. Using this method, part of page might not display.

    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  3. Duane Arnold 3,211 Reputation points
    2021-07-12T10:04:25.453+00:00

    IMHO, you should remove all try/catches out the code and let a centralized location catch and log the exception including the exception message, stack trace and inner.exception.message if not null and redirect to an Error page indicating that an error has occurred a user friendly message and not exposing the exception to the user.

    https://stackify.com/csharp-catch-all-exceptions/

    There are logging frameworks like Log4NET that can also log to a database table you should look into.

    HTH

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.