In .NET, the default exception handler will let the user continue running the program. However, I'd like to have a global exception handler that saves the stack trace to an "errorlog.txt" file so the user can send it to me and doesn't have to remember to click "Details" and copy it out of the dialog (and remove all the useless crap about loaded assemblies and such). But when I do this, the code doesn't know how to continue, so all I can do is exit the app. Is there any way to have the best of both worlds? (Yes, I know what I'm asking for is essentially "On Error Resume Next" with logging, but I really think it would be useful!)
The Controller Advice class to handle the exception globally is given below. We can define any Exception Handler methods in this class file. The Product Service API controller file is given below to update the Product. If the Product is not found, then it throws the ProductNotFoundException class.
Although C does not provide direct support to error handling (or exception handling), there are ways through which error handling can be done in C. A programmer has to prevent errors at the first place and test return values from the functions.
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.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
If you bind yourself to this event when the application starts, you should be able to catch any Unhandled Exception your application throws, and save it to a file. (Use the Exception
object part of the UnhandledExceptionEventArgs
. I do not believe it is possible to resume from where the error Occurred.
You can write a global exception handler method that you call in every catch
block, which writes the stack trace where ever you want to save it. But you'd need to write try . . . catch
blocks for every operation that needs them and call the exception handler in each.
You can also call that global exception handler method in the MyApplication.UnhandledException
handler for all unhandled events. But when control gets to that method in that case, the program is not going to continue running.
No that does not exist, exceptions are a flow control construct, so On Error Resume Next
is not possible.
You could do your operation in a loop and on an exception, retry your logic.
KandallFrey is right however, you shouldn't use exceptions as flow control, use them only in exceptional cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With