0

I'm trying to develop a dll project in C# which has to be able to catch all unhandled exceptions of the project that references it.

The idea is include this dll in any type of project (mvc, web api, other dll projects) and catch and log in a DB the exceptions with their entire call stacks to be able to reproduce them.

The problem is that I cannot use the currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler); because I'm in a dll project and there is not main method.

In the other hand, how can I register this dll in the projects to be able to catch their errors? Is it necessary to register something in the config file?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Dalamar
  • 107
  • 1
  • 1
  • 7
  • You don't have to be in the `main method` – Renat Jan 22 '20 at 11:09
  • 1
    You need to call some method from your assembly anyway (otherwise it will not load), so why not to create some public static class method and call it from your main method (like `UnhandledExceptionsLogger.Register();`) – vasily.sib Jan 22 '20 at 11:13
  • Because I have no main method. The dll could be referenced by an API project wich has no main method – Dalamar Jan 22 '20 at 15:16

1 Answers1

0

My first thought here would be to keep to handler for the unhandled exception in you application and pass the exception to the class library, you could add extra parameters which hold information from your current domain, which then is logged to a file/db.

My recommandation whould be to use some kind of facade/singleton pattern as the only entrypoint to your class library, which will force all referencing application to use the same logic

  • But what if my class library is referenced by an API project? there is no main method in wich to add the handler. In fact, I don't want whoever implements my class library to have to add any code. I wanted that at most one line would be needed in the config file. – Dalamar Jan 22 '20 at 15:24
  • I think there are a few different scenarios in play here, if a class library references you class library to handle the exceptions, they should provide a main point which catches all unhandled exceptions and delegate it to your library, for a web api you might want to look at middleware [link](https://learn.microsoft.com/nl-be/aspnet/core/fundamentals/middleware/write?view=aspnetcore-3.1&viewFallbackFrom=aspnetcore-2.0) to do the same thing – Jochem Van Hespen Jan 22 '20 at 16:06
  • Is there any way to do the same in .Net 4.x? – Dalamar Jan 22 '20 at 21:24
  • I think an httpmodule is the thing you are looking for in .net 4.x [link](https://support.microsoft.com/en-us/help/307985/info-asp-net-http-modules-and-http-handlers-overview) – Jochem Van Hespen Jan 23 '20 at 08:32