Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A global error handler for a class library in C#

Is there a way to catch and handle an exception for all exceptions thrown within any of the methods of a class library?

I can use a try catch construct within each method as in sample code below, but I was looking for a global error handler for a class library. The library could be used by ASP.Net or Winforms apps or another class library.

The benefit would be easier development, and no need to repeatedly do the same thing within each method.

public void RegisterEmployee(int employeeId)
{
   try
   {
     ....
   }
   catch(Exception ex)
   {
     ABC.Logger.Log(ex);
   throw;
   }
}  
like image 557
Sunil Avatar asked Jul 26 '13 03:07

Sunil


People also ask

What is global error handling?

Global Error Handler This method is called whenever an error is thrown somewhere in the application. The error is passed as a parameter and can be processed further inside the method. In our case a dialog is opened where the error message should be displayed and the error is logged to the browser console.

What is global exception handling in C#?

An ExceptionFilterAttribute is used to collect unhandled exceptions. You can register it as a global filter, and it will function as a global exception handler. Another option is to use a custom middleware designed to do nothing but catch unhandled exceptions.

How do you handle global exception?

In the Design tab part of the Ribbon, select New > Global Handler. The New Global Handler window opens. Type in a Name for the handler and save it in the project path. Click Create, a Global Exception Handler is added to the automation project.

Which level of error handling is handler catches all exceptions?

Page Level Error Event Handling This code example shows a handler for the Error event in an ASP.NET Web page. This handler catches all exceptions that are not already handled within try / catch blocks in the page.


1 Answers

You can subscribe to global event handler like AppDomain.UnhandledException and check the method that throws exception:

AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;

private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
    var exceptionObject = unhandledExceptionEventArgs.ExceptionObject as Exception;
    if (exceptionObject == null) return;
    var assembly = exceptionObject.TargetSite.DeclaringType.Assembly;
    if (assembly == //your code)
    {
        //Do something
    }
}
like image 64
Vyacheslav Volkov Avatar answered Sep 18 '22 23:09

Vyacheslav Volkov