C
C#•5mo ago
PurplePeopleEater

Automatically logging all errors without using try-catch

Is there a way to automatically log all errors without using try-catch's. For example, I could write the following pseudo-code: try { func-that-could-cause-an-error-to-be-thrown(); } catch { logfunc(...); } by using try-catch, but I would like the logging to happen WITHOUT the try-catch and WITHOUT the logfunc(...) call. The reason I want this is because I don't want to add try-catches to the entire large code base - it would require many, many edits. The errors only seem to be thrown once every few hours to once every few days depending on the situation so it is problematic to always run the app via Visual Studio to see the errors because the errors happen so infrequently. When running my app in Visual Studio the debugger captures the errors for me and shows them... which is great except that I don't want to run my app in Visual Studio. That said, I want any error that would be shown in the debugger to be the errors that get logged. I am open to logging via file or via the Windows Events though I would prefer via file. I am open to using some built in logging feature of C#, or a logging library, etc. Thank you in advance for any help.
20 Replies
Angius
Angius•5mo ago
Exceptions bubble up You don't have to catch them at the point where they occur You could just as easily have a global handler like
try {
new App().Run();
} catch (Exception e) {
Log.Error(e.Message);
}
try {
new App().Run();
} catch (Exception e) {
Log.Error(e.Message);
}
Far as where to log them... the most common way is probably using the Serilog library It has a selection of sinks, which is where your logs go It can be a file, a database, an email, hell, even a Discord server
Jimmacle
Jimmacle•5mo ago
you can also add a handler to the appdomain's unhandled exception event
PurplePeopleEater
PurplePeopleEater•5mo ago
Thank you ZZZZ, I like this solution. But will it work even for places where I am using Task.Run?
Angius
Angius•5mo ago
Why would you use Task.Run()? As long as there are no async voids and everything async gets awaited, it should be fine
Jimmacle
Jimmacle•5mo ago
AppDomain.CurrentDomain.UnhandledException
TaskScheduler.UnobservedTaskException
AppDomain.CurrentDomain.UnhandledException
TaskScheduler.UnobservedTaskException
are the relevant events if you just want to handle anything afaik
PurplePeopleEater
PurplePeopleEater•5mo ago
I use Task.Run because my app is responding to events in Windows that are happening such a the creation of new windows. My app needs to do processing on each new window that is being created but that processing can take a long time and the app needs to continue to listen for new windows being created. That is why I was using Task.Run to handle the processing step.
Angius
Angius•5mo ago
Gotcha
PurplePeopleEater
PurplePeopleEater•5mo ago
Looking at my code, I do not see any async void's, but I also do not think I am awaiting - I specifically want things to happen asynchronously. Thank you jIMMACLE, I am not familiar with this method at all
Angius
Angius•5mo ago
So you want fire and forget?
PurplePeopleEater
PurplePeopleEater•5mo ago
Yes, I am fire and forget
Angius
Angius•5mo ago
If so, then each task you fire and forget should handle the exceptions
PurplePeopleEater
PurplePeopleEater•5mo ago
Yes, that is what I am thinking too
Angius
Angius•5mo ago
It doesn't need to be handled anywhere deep, though. Exception bubbling is still a thing
PurplePeopleEater
PurplePeopleEater•5mo ago
Unless maybe jIMMACLE's method provides a way to declare that I need logging in a single place? Yes, I get what you are saying
casog
casog•5mo ago
You can use centralized exception handling in middleware by setting your applicationbuilder to "UseExceptionhandler()". Ihttps://andrewhalil.com/2022/03/10/centralized-logging-and-exception-handling-in-a-net-core-application/
Andrew Halil
andrewhalil.com
Centralized Logging and Exception Handling in a .NET Core Application
Welcome to today’s post. In today’s post I will be discussing how to use error handling and diagnostics logging middleware to trap and process unhandled errors from a .NET Core API. One useful tactic for handling unhandled errors within an application is to create a centralized error handling method or delegate that can trap the exception ...
PurplePeopleEater
PurplePeopleEater•5mo ago
Thank you CASOG, but it isn't clear to me, does this also apply to an application like mine which is a WPF desktop app?
casog
casog•5mo ago
Never used WPF 😦 Sorry Seems not, but there are patterns you can use. Maybe a CQRS pattern with a exception / logging handler at the highest level of the stack, the place where the services/data is queried It's an application/structure design decision, it has to be built in when you imagine the program or added later
PurplePeopleEater
PurplePeopleEater•5mo ago
Ok, thank you again
casog
casog•5mo ago
Task.run has a parameter for a cancellation token, just one reason I can think of
Unknown User
Unknown User•5mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server
More Posts
why is this while loop infinite?this is crashing unity: (complete beginner btw literally just started messing around with code 2 dayTips on error handlingI'm currently using OneOf to handle errors. For example: ```csharp public async Task<OneOf<None, N✅ Trying to send message to a specific user in signalR but javascript is just not recieving the dataTrying to send message to a specific user in signalR but javascript is just not recieving the data IOnline solo class for learning Cloud Azure.Hi, can someone recommend good online course/training with /expert/interesting/ho to feel/ Cloud Social Media & AI .Hi All, Just a quick question for those interested in AI technology, specifically with Social MediaVisual Studio 2022 winforms problemEror: CS1061 ```csharp private void btn_Giris_Click(object sender, EventArgs e) { if (!sCombine string formatting (eg `$"{number:N2}" with D2) so like `{number:N2D2}`)You have string interpolation like $"{number:N2}", how can I combine formats? Like $"{number:N2D2}".NET MAUI Android Error: Type androidx.collection.ArrayMapKit is defined multiple timesthis error happens to me when i download firebase storage or firebase firestore plugins. New projectI'm getting "specified method is not supported" when I include a specific navigation property with eI'm using ASP.NET Core Identity with a custom IdentityUser that looks like this: public class AppliIs there a way to authenticate using OAuth2 token and map it to internal JWTBasically, my server checks for some stuff by utilizing OAuth2 token and returns JWT Im looking for