registering UnhandledException of AppDomain WPF - wpf

I am registering to un-handled exception of my WPF Application.
After UnhandledExceptionHandler invokes, the application will close automatically ? Or do I need to call ShutdownProcess();
Is this enough ?
static void Main(string[] args)
{
//Register to unhandled exception for this application
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
try
{
Exception ex = (Exception)args.ExceptionObject;
_logger.ErrorFormat("Process caught unhandled exception, Exception = {0}", ex);
ShutdownProcess();
}
catch
{
// swallow silently... nothing we can do.
}
}

From MSDN:
"This event provides notification of uncaught exceptions. It allows
the application to log information about the exception before the
system default handler reports the exception to the user and
terminates the application."
So the ugly Popup will be displayed regardless what you are doing in your Handler and the application will be terminated after that.
If you don't want the default error popup to be displayed you should add a handler to Application.Current.DispatcherUnhandledException log your errors and call Application.Current.Shutdown() yourself.

Related

WinForms exception interceptor

I'm using the ABP framework with WinForms and I need to identify the best way to intercept an exception and log this information.
My WinForms is a Multiple-Document Interface (MDI) application. I add a HandleException in Program.cs so that when the application throws an exception, I'm able to log it in the log file. But if I get an exception in an ApplicationService, this exception is handled by ABP and not thrown back to WinForms, and nothing is written in the log file.
Do I need to implement some interface to have the classic logging like MVC/Angular app?
UPDATE
I found that the problem is related to async operation. Usually I call:
await _service.GetProducts();
If an exception is thrown, the main thread does not intercept it. If I switch to:
AsyncHelper.RunSync(() => _service.GetProducts());
Then the main thread intercepts the error.
because the exception is thrown in another thread you have to handle unhandled exceptions of the application domain. insert the exception handler into the starting point of your application. for win forms i guess you can use program.cs
static class Program
{
[STAThread]
static void Main(string[] argv)
{
try
{
AppDomain.CurrentDomain.UnhandledException += (sender,e)
=> HandleException(e.ExceptionObject);
Application.ThreadException += (sender,e)
=> HandleException(e.Exception);
Application.Run(new MainWindow());
}
catch (Exception ex)
{
HandleException(ex);
}
}
static void HandleException(object exception) {
var ex= exception as Exception;
if (ex== null) {
ex= new NotSupportedException("Unhandled exception: " + exceptionObject.ToString());
}
//you can log exception here -> ex.ToString();
}
}
Ok after some invastigation and googling I found this MSDN explanation Asynchronous Programming - Async from the Start
Accoriding to this article I change my program start to move to async code.
I need to chage a little bit more because I'm on Mdi Form when open a inside form
Form1 childForm = Globals.Bootstrapper.IocManager.Resolve<Form1>();
childForm.MdiParent = this;
var formAsync = childForm.InitializeAsync();
FormExtension.HandleExceptions(formAsync);
childForm.Show();
I add the static class to intercept the error form Abp
public static async void HandleExceptions(Task task)
{
try
{
await Task.Yield(); //ensure this runs as a continuation
await task;
}
catch (Exception ex)
{
//deal with exception, either with message box
//or delegating to general exception handling logic you may have wired up
//e.g. to Application.ThreadException and AppDomain.UnhandledException
var log = Globals.Bootstrapper.IocManager.IocContainer.Resolve<ILogger>();
LogHelper.LogException(log, ex);
//Exception handling...
MessageBox.Show("Ops!" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//Application.Exit();
}
}
Now my log file is populated in correct way

Duplex channel callback calls method that throws exception. Where does the execption go?

And how can I present it to the user?
This post : WCF Duplex: How to handle thrown exception in duplex Callback is very close to my scenario. And this post is useful for helping me re-establish the connection when the channel is faulted.
I have a Publishing application Pub, and a subscribing WPF application Sub. The Pub sends a message and the Sub has subscribed for a callback using a duplex channel.
Sub.ViewModel.ReactToChange(sender, e) tries to read some data, but is unable to and throws an exception.
DispatcherUnhandledException doesn't catch it (I didn't really expect it to.)
AppDomain.CurrentDomain.UnhandledException doesn't catch it (that does surprise me)
The end result is I have an application that is still running, and no exception message is shown to the user so they can correct the problem. Is there a way I can show that exception to the user?
This is a bit tricky, but the only way I've found. I hope this helps others.
The idea is to not let an exception get thrown, but instead create an UnhendledExceptionEventArg and pass it up to your UI layer. Here is some example code:
public class BuggySubscriber : IDisposable
{
public BuggySubscriber(string dataSourceName)
{
SyncContext = SynchronizationContext.Current;
Subscriber = new MockSubscriber(dataSourceName);
Subscriber.Refreshed += OnDataChanged;
}
public SynchronizationContext SyncContext { get; set; }
public event EventHandler<UnhandledExceptionEventArgs> ExceptionOccurred;
// Bouncing Exception Step 3
private void OnExceptionOccured(Exception ex)
{
var callback = new SendOrPostCallback(delegate
{
var handler = ExceptionOccurred;
if (!ReferenceEquals(handler, null))
handler(this, new UnhandledExceptionEventArgs(ex, true));
});
SyncContext.Post(callback, null);
}
void OnDataChanged(object sender, ServiceModel.DataChanged.DataChangedEventArgs e)
{
// Bouncing Exception Step 1 & 2
OnExceptionOccured(new NotImplementedException());
}
So this is the "Sub" code. In the WPF application I add the following when the app starts:
protected override void OnStartup(StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
BuggySubscriber.ExceptionOccurred += Sub_ExceptionOccurred;
...
}
// Bouncing Exception Step 5
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = e.ExceptionObject as Exception;
if (!ReferenceEquals(exception, null))
ShowErrorMessage(exception);
}
// Bouncing Exception Step 4
void Sub_ExceptionOccurred(object sender, UnhandledExceptionEventArgs e)
{
var exception = e.ExceptionObject as Exception;
if (!ReferenceEquals(exception, null))
throw exception;
}
So now let's try to follow the bouncing exception.
In real life, the subscriber was notified and an exception occurs and is caught. (In my sample, I don't show that.)
Then the OnExceptionOccurred(Exception ex) is called.
That then creates the SendOrPostCallback using the ExceptionOccurred event and then does a Post to the current SynchronizationContext.
The WPF application that registered for the ExceptionOccurred (Now if you like, you could handle the exception message here... I chose to use two paths for exceptions rather than three.) It casts and throws the Exception.
Now the CurrentDomain_UnhandledException processes it and shows an error message to the user (right before it exits).
I'm sure there are many variations on this, but this does show some of the trickier code that I could not find in one place.
NOTE: This does not solve any channel problems. If you have an exception you can recover from you will still need to reestablish the channel since it will be faulted or closed.

WPF handling missing dlls

I have noticed that in some situations, where I do not distribute a particular dll, which is required by application, the application doesn't not provide any errors, it just does not load (show on screen). It behaves like you haven't started it.
Does anyone know why is this happening?
Edit: Steps to reproduce:
Create a solution with WPF app project and class library project (ReferenceDll).
Add reference in WPF app project to class library project.
In class library, add this method to Class1
public int Calculate(int a, int b)
{
return a + b;
}
place this code in App.OnStartup:
try
{
int result = new ReferenceDll.Class1().Calculate(2, 4);
}
catch (Exception ex)
{
File.WriteAllText(#"D:\Test\error.txt", ex.ToString());
}
build the solution then remove the ReferenceDll from the bin folder. Run the app.
No file will be created, app will not show. Even if you move Try catch code in the main view, in some button click event, Catch{} will never be fired and it will display non-informative message
AppName has stopped working.
and offer options to debug, which is of no use to end-user.
If you don't have any Trace.WriteLine statements, then I suggest you add some. Add some to the exception handlers. Also you could use the following free tool to capture trace and try and narrow it down that way.
http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx
You could also override the Onstartup method in app.xaml.cs and instantiate your application from there and catch any exceptions and output to trace.
Update
I have tried the steps that you have indicated in your update and the application loaded without any problems. The next thing that I would suggest would be to check what version of the .net framework that you have on your environment that you have deployed to. Look at this link, if you need help to do that:
http://msdn.microsoft.com/en-us/kb/kbarticle.aspx?id=318785
Update
Put your error logging in a handler like the one in the answer to this question and you will see the error. Just tried this with your example and it worked. The error tells you exactly what is wrong:
System.IO.FileNotFoundException: Could not load file or assembly 'ReferenceDll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
File name: 'ReferenceDll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
at WPFApp.App.OnStartup(StartupEventArgs e)
at System.Windows.Application.<.ctor>b__1(Object unused)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog
WPF window crashes on startup, or it starts but hangs and does not render contents
That may happen when the exception is thrown on a secondary thread. See remarks section on this page:
Standalone or browser-hosted WPF applications use the Application class to detect unhandled exceptions (see DispatcherUnhandledException). However, Application can only detect unhandled exceptions that are thrown on the same thread that the Application class is running. Usually, an application will have one main user interface (UI) thread, so the unhandled exception detection behavior of the Application class is adequate. However, unhandled exceptions that are thrown on secondary threads are not automatically detected by the Application class on the main UI thread.
You can try using this event to catch detect the exception and log the error:
AppDomain.UnhandledException Event
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
static void MyHandler(object sender, UnhandledExceptionEventArgs args) {
Exception e = (Exception) args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
}
UPDATE:
Apart from the threading issue it also can the cause if you put your try...catch block to the wrong place. Consider this example:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Do();
}
private void Do()
{
try
{
int result = new ClassLibrary1.Class1().Calculate(2, 4);
}
catch (System.Exception ex)
{
Console.WriteLine("MyHandler caught by try...catch: " + ex.Message);
}
}
}
This will result in an exception at the line where the Do() is called since the CLR here tries to resolve the assembly at this point. The exception is not caught and the app terminates.
But if you try this one:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
try
{
Do();
}
catch (System.Exception ex)
{
Console.WriteLine("MyHandler caught by try...catch: " + ex.Message);
}
}
private void Do()
{
int result = new ClassLibrary1.Class1().Calculate(2, 4);
}
}
The output is:
MyHandler caught by try...catch: Could not load file or assembly 'ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
Note that the UnhandledException event is not fired when you subscribe to it in the same function where the assembly is referenced. This works as well:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(
(sender, args) =>
{
Exception ex = (Exception)args.ExceptionObject;
Console.WriteLine("MyHandler caught by UnhandledException handler: " + ex.Message);
});
Do();
}
private void Do()
{
int result = new ClassLibrary1.Class1().Calculate(2, 4);
}
Result:
MyHandler caught by UnhandledException handler: Could not load file or assembly 'ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
Hope it helps.

WPF - DispatcherUnhandledException does not seem to work

I started a new WPF project in VS2008 and then added some code to trap DispatcherUnhandledException. Then I added a throw exception to Window1
but the error is not trapped by the handler. Why?
public App()
{
this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
}
void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
System.Windows.MessageBox.Show(string.Format("An error occured: {0}", e.Exception.Message), "Error");
e.Handled = true;
}
void Window1_MouseDown(object sender, MouseButtonEventArgs e)
{
throw new NotImplementedException();
}
This can happen because of the way you have the debugger handling exceptions -- Debug/Exceptions... should allow you to configure exactly how you want it handled.
Look at following msdn link http://msdn.microsoft.com/en-us/library/system.windows.application.dispatcherunhandledexception.aspx
Following is Relevant here
If an exception is not handled on either a background user interface (UI) thread (a thread with its own Dispatcher) or a background worker thread (a thread without a Dispatcher), the exception is not forwarded to the main UI thread. Consequently, DispatcherUnhandledException is not raised. In these circumstances, you will need to write code to do the following:
Handle exceptions on the background thread.
Dispatch those exceptions to the main UI thread.
Rethrow them on the main UI thread without handling them to allow DispatcherUnhandledException to be raised.
This is how I handle it. This isn't pretty but keep in mind that this type of error should never make it past debugging as a dev. Those errors should be long resolved before you go to production (so its okay that this isn't pretty). In the Startup project, in the App.xaml (App.xaml.cs) code behind, I put the following code.
OnStartup, create a DispatcherUnhandledException event handler
In the handler, use a MessageBox to display the message. Note that its likely the startup window has not yet been created so don't try to put it in a window.
e.Handle the error
I like to see when there are additional internal errors so I continue to call the display window until the internal error is null.
I'm not sure why the code block special characters aren't formatting this correctly. Sorry about that.
protected override void OnStartup(StartupEventArgs e)
{
// define application exception handler
Application.Current.DispatcherUnhandledException +=
AppDispatcherUnhandledException;
// defer other startup processing to base class
base.OnStartup(e);
}
private void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
runException(e.Exception);
e.Handled = true;
}
void runException(Exception ex)
{
MessageBox.Show(
String.Format(
"{0} Error: {1}\r\n\r\n{2}",
ex.Source, ex.Message, ex.StackTrace,
"Initialize Error",
MessageBoxButton.OK,
MessageBoxImage.Error));
if (ex.InnerException != null)
{
runException(ex.InnerException);
}
}
At first, even outside the debugging environment, my handler does not seem to be triggering.....then I realized I forget to set e.Handled = true.
In truth it was working but because e.Handled was still false the standard exception handler still kicked in and did its thing.
Once I set e.Handled = true, then everything was hunky dory. So if its not working for you, make sure you've done that step.
For those interested
It seems that the IDE is still breaking on exceptions and that if you click continue in the IDE it call the error handler.

How can I get the current exception in a WinForms TraceListener

I am modifying an existing WinForms app which is setup with a custom TraceListener which logs any unhandled errors that occur in the app. It seems to me like the TraceListener gets the message part of the exception (which is what gets logged), but not the other exception information. I would like to be able to get at the exception object (to get the stacktrace and other info).
In ASP.NET, which I am more familiar with, I would call Server.GetLastError to get the most recent exception, but of course that won't work in WinForms.
How can I get the most recent exception?
I assume that you have set an event handler that catches unhandled domain exceptions and thread exceptions. In that delegate you probably call the trace listener to log the exception. Simply issue an extra call to set the exception context.
[STAThread]
private static void Main()
{
// Add the event handler for handling UI thread exceptions
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
// Add the event handler for handling non-UI thread exceptions
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
...
Application.Run(new Form1());
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MyTraceListener.Instance.ExceptionContext = e;
Trace.WriteLine(e.ToString());
}
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
// similar to above CurrentDomain_UnhandledException
}
...
Trace.Listeners.Add(MyTraceListener.Instance);
...
class MyTraceListener : System.Diagnostics.TraceListener
{
...
public Object ExceptionContext { get; set; }
public static MyTraceListener Instance { get { ... } }
}
On the Write methods in MyTraceListener you can get the exception context and work with that. Remember to sync exception context.

Resources