1

I have a C# class library project and I need to capture all unhandled exceptions in my class even if I not use try catch blocks. Note: I have already installed log4net with log4net.config and it works fine logging manually in Debug,Info,Error.

Can you help me?

thanks

ezechiele2517
  • 375
  • 1
  • 5
  • 19
  • what type of technology your are using ? for example if asp.net you can put in application_error in global.asax. – Hany Habib May 23 '18 at 13:27
  • Check this global error handler: https://stackoverflow.com/questions/17872620/a-global-error-handler-for-a-class-library-in-c-sharp – st_stefanov May 23 '18 at 13:28
  • I'm using asp.net c# class library project and I don't have global.asax file in my project. Can I add it if I'm not in web context? – ezechiele2517 May 23 '18 at 13:32
  • @HanyHabib I'm using asp.net c# class library project and I don't have global.asax file in my project. Can I add it if I'm not in web context? – ezechiele2517 May 23 '18 at 13:38
  • Possible duplicate of [A global error handler for a class library in C#](https://stackoverflow.com/questions/17872620/a-global-error-handler-for-a-class-library-in-c-sharp) – kͩeͣmͮpͥ ͩ May 23 '18 at 13:39
  • @DavidKemp It's a dll library project and I don't have main class to put handler inside it. how can I do ? – ezechiele2517 May 23 '18 at 13:49
  • I'd argue exception handling is not your problem - I don't expect Microsoft's assemblies to log all the exceptions they handle. Log *why* the exception is thrown if you throw it - that's far more useful than just knowing an exception was thrown. – kͩeͣmͮpͥ ͩ May 23 '18 at 15:16

1 Answers1

0

I had to do the same and this post was helpful. The only downside to this is that you may end up logging too many exceptions. Since you say you are writing a class library, depending on the application that will use your library, you may not want to catch all the exceptions thrown by the application. To solve this issue, I recommend doing something like:

AppDomain.CurrentDomain.FirstChanceException += (sender, e) => {
    if (e.Exception.TargetSite.DeclaringType.Assembly == Assembly.GetExecutingAssembly())
    {
        logger.ErrorFormat("Exception Thrown: {0}\n{1}", e.Exception.Message, e.Exception.StackTrace);
    }
};

This way, you will only catch exceptions from your code. Hope this helps !