5

I am building a console app that basically just make calls to the Database's Store Procedures. This works fine, but now I've came across this little issue - Error Handling.

I'm using Serilog to log any errors I get into a text file, but the issue I'm getting with this is that I have to do a try-catch everywhere. Of course, for a little software, using and put try-catch isn't much of a pain, but when it comes to building large softwares, I'm guessing you can sometime forget to put in error-handling codes?? So I was wondering if there's a way where I can tell Serilog to log and print out the error whenever there is one as a default??

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Danny
  • 9,199
  • 16
  • 53
  • 75
  • Add an event handler for `System.AppDomain.CurrentDomain.UnhandledException` and log the error in the handler - see [this question](http://stackoverflow.com/questions/3133199/net-global-exception-handler-in-console-application) – stuartd Jan 10 '17 at 11:57
  • 1
    @stuartd Ah, sorry - forgotten to mention I'm using ASP.NET CORE. Seems like they took out AppDomain :( – Danny Jan 10 '17 at 12:08
  • https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling has some options – stuartd Jan 10 '17 at 12:12
  • 1
    Exception handling middleware? – juunas Jan 10 '17 at 14:20
  • This might help: https://github.com/datalust/serilog-middleware-example/blob/master/src/Datalust.SerilogMiddlewareExample/Diagnostics/SerilogMiddleware.cs – Volkmar Rigo Apr 09 '19 at 19:08

1 Answers1

0

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

static void Main(string[] args)
{
  Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
  AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

 
  //do something with the file contents
}

static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
  // Log the exception, display it, etc
  
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
  // Log the exception, display it, etc
  
}
  • which namespace has "Application" ? I'm using a .net 7 console app (without static void Main) and it tries to resolve with System.Net.Mime.MediaTypeNames but obviously is not the correct one... anyway the CurrentDomain event works ok... – SandroRiz Apr 13 '23 at 12:38