Application.UnhandledException and original exception message - windows-8

I'm trying to access original exception which caused UnhandledException but all I see is text contained at UnhandledExceptionEventArgs.Message property;
For example:
I have view with button with click handler:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
throw new NullReferenceException("Test exc");
}
At App constructor I have subscribed to UnhandledException exception
this.UnhandledException += App_UnhandledException;
private void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Debug.WriteLine(e.Message);
Debug.WriteLine(e.Exception.ToString());
}
As a result I have no option to get original exception text "Test exc". All I have is
Message = System.NullReferenceException at
W8.Controls.SearchControl.Button_Click_1(Object sender,
RoutedEventArgs e)
Exception = System.NullReferenceException: Object reference not set to
an instance of an object.
Thanks in advance for advise!

There are some limitations in what gets propagated to a UnhandledException. As documented:
Another limitation is that the UnhandledException event arguments
don’t contain as much detail as the original exception. Whenever
possible, if the application requires specific processing of a certain
exception, it’s always better to catch the exception as it propagates,
since more detail will be available. The UnhandledException event
arguments expose an exception object through the Exception property.
However, the type, message, and stack trace of this exception object
are not guaranteed to match those of the original exception that was
raised. The event arguments also expose a Message property. In most
cases, this will contain the message of the originally raised
exception.

Related

How to catch exception with action composition in Play 2.3.X

I'm developing an application using Play 2.3.1.
I'm annotating all my controllers with the following Action :
#Override
public Promise<Result> call(final Context ctx) throws Throwable {
try {
return delegate.call(ctx);
} catch (MyCustomException e) {
return handleCustomException(e);
} catch (Exception e) {
return handleUnexpectedError(e);
}
}
The aim of this action is to catch any exception thrown by a controller method in order to send a clean message to the user.
MyCustomException is my application specific exception that extends Exception.
The problem is that even if I throw a MyCustomException in the method of my controller, the corresponding catch statement is never executed.
I always have a RuntimeException caused by my MyCustomException.
The consequence is that no matter what exception occured, the user always sees the result sent by handleUnexpectedError(e).
What am I doing wrong ? Thanks.
After some investigation, the guilty is the Security action of Play.
More details here : https://groups.google.com/forum/#!topic/play-framework/AY4NuQziYyM
Because I added my custom actions at AbstractController level and the #Authenticated(Authenticator.class) annotation at the controller level, the security action composition is the last one to be executed.
Because of the Security.java at line 51, even if my exception is expected, Play throws a RuntimeException.
So the solution is to add the security annotation at method level in order to be sure that it is executed before the first execution of the method.

NavigationService.Navigate throws an exception and invokes Application_UnhandledException in WP8

I am developing a simple WP8 application using VS 2013. I have a MainPage.xaml and added a new page called Page1.xaml. I have a list of options on screen when a user clicks on "new item" I want to open a new page to add new item (Page1.xaml for instance).
On the list selection changed event I have written the following code:
private void OptionssList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selection = (MenuItem) e.AddedItems[0];
switch (selection.Id)
{
case 0:
break;
case 1:
break;
case 2:
this.NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
break;
case 3:
break;
default:
break;
}
}
When I try to debug the application, I notice that the constructor of Page1.xaml is invoked if I had an OnNavigatedTo event handler it is also been invoked however after all this an Unhandled exception is thrown. There is no code that I can see when the exception is thrown however it invokes the Application_UnhandledException event handler.
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
The exception details is as shown below:
System.NullReferenceException was unhandled
Message: An unhandled exception of type 'System.NullReferenceException' occurred in System.Windows.ni.dll
Additional information: Object reference not set to an instance of an object.
I would like to know if I am missing something. I referred to the sample it also shows similar way to Navigate, did not notice any things fancy.
i know this may be a very stupid question, your code looks fine to me, is your page not maybe in another folder? I always put my pages in a folder called UI, so my code will look something like this:
/folder1/folder2/pagename
this.NavigationService.Navigate(new Uri("/UI/Generics/Page.xaml", UriKind.Relative));
Just make sure of that, cause that usually get me.

Cannot navigate to another page

I have a button and a tapped event:
private void btnSetLocationName_Click_1(object sender, RoutedEventArgs e)
{
ApplicationModel.LocationName = locationName.Text;
Frame.Navigate(typeof(GroupsPage));
}
I want to just navigate to another page. Unfortunately, Frame.Navigate does not work. I have also tried to make sure it runs in the GUI thread:
await this.Dispatcher.RunAsync(CoreDispatcherPriority.High, () => Frame.Navigate(typeof(GroupsPage)));
However, it should do, as the click handler for the button runs in the GUI thread.
The following error occurs:
Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))
OK, after commenting out bits of code until it worked, it turns out I had an empty OnNavigatedTo override:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//base.OnNavigatedTo(e);
}
If you uncomment base.OnNavigatedTo it now works.
I think what threw me was that the error occurred when navigating FROM a page with this empty override. Also, the cryptic error message didn't help much.

Unhandled exception handler not called for Metro / WinRT UI async void event handler

Consider the following to be extracts from a Windows 8 Metro / WinRT app, which have been reduced to the bare minimum required to show the anomaly:
public class App : Application
{
public App()
{
UnhandledException += (sender, e) => e.Handled = true;
}
}
public class MainPage : Page
{
private void Button_Click_1(object sender, RoutedEventArgs e)
{
throw new NotSupportedException();
}
private async void Button_Click_2(object sender, RoutedEventArgs e)
{
throw new NotSupportedException();
}
}
So given a Metro UI with two buttons and their click event handlers, the only difference is that the second event handler is marked as async.
Then clicking on each button, I would expect the UnhandledException handler to be called in both cases, since they (should) both be entered via the UI thread and associated synchronization context.
My understanding is that, for async void methods, any exceptions should be captured and 'rethrown' (preserving the original stacktrace) via the initial synchronization context, which is also clearly stated in the Async / Await FAQ.
But the UnhandledException handler is not called in the async case, so the application crashes! Since this challenges what I consider an otherwise very intuitive model, I need to know why! Yes, I know I could wrap the body of the handler in a try { } catch { }, but my question is why isn't the backstop UnhandledException handler called?
To further emphasise why this doesn't make sense, consider the following practically identical extracts from a WPF app also using async / await and targeting .NET Framework 4.5:
public class App : Application
{
public App()
{
DispatcherUnhandledException += (sender, e) => e.Handled = true;
}
}
public class MainWindow : Window
{
private void Button_Click_1(object sender, RoutedEventArgs e)
{
throw new NotSupportedException();
}
private async void Button_Click_2(object sender, RoutedEventArgs e)
{
throw new NotSupportedException();
}
}
[There is a subtle difference that WPF has both an Application DispatcherUnhandledException event handler as well as an AppDomain UnhandledException event handler, but you can only mark the exception as 'handled' in the DispatcherUnhandledException, which aligns with the Metro / WinRT Application UnhandledException event handler above.]
Then clicking on each button, the DispatcherUnhandledException handler is indeed called in both cases, as expected, and the application does not crash.
Answered here: No UnhandledException fired from async event callback
It is a known limitation of WinRT. Hopefully, it gets fixed in the next update.
The solution in the following post worked for me, with one small change: I had to move AsyncSynchronizationContext.Register(); to the App.OnLaunched event
http://www.markermetro.com/2013/01/technical/handling-unhandled-exceptions-with-asyncawait-on-windows-8-and-windows-phone-8/
As explained in the documentation (source: http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.application.unhandledexception.aspx):
It’s important to be aware of several limitations of the
Application.UnhandledException event. This event is only used with
exceptions encountered by the XAML framework. Exceptions encountered
by other Windows Runtime components or parts of the application that
are not connected to the XAML framework will not result in this event
being raised.
For example, if a different Windows component calls
into application code and an exception is thrown and not caught, the
UnhandledException event won’t be raised. If the application creates
a worker thread, and then raises an exception on the worker thread,
the UnhandledException event won’t be raised.
As pointed out in this conversation, only way to retrieve exceptions happening in a worker thread is to wrap them in a try/catch block. As a consequence, here's the workaround I'm using in my app: instead of using Task.Run or equivalents to execute code on a worker thread from the UI, I'm using this method:
/// <summary>
/// Runs code in a worker thread and retrieves a related exception if any.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="action">The action.</param>
public static void SafeRun(this DependencyObject target, Action action)
{
Task task = ThreadPool.RunAsync(o =>
{
try
{
action();
}
catch (Exception ex)
{
/* Call the same error logging logic as in the UnhandledException event handler here. */
}
}).AsTask();
task.Wait();
}
Bottom line is that to log all errors in your app, you should:
Subscribre to the UnhandledException event to get XAML stack related errors,
Wrap actions happening in a worker threads in a try/catch block.
From my point of view the only right answere was downvoted here (Try UnobservedTaskException event of TaskScheduler)
the problem is that you are using 'async void' where the exceptions cannot be handled. This is not a WinRT limitation but as design behaviour of async. You need to understand the async deeply to correctly implement exception handling here. See this article: http://msdn.microsoft.com/en-us/magazine/jj991977.aspx
Exceptions are rethrown whe GC collects the tasks as unobserved. You can get them by registering TaskScheduler UnobservedTaskException event. Note - it takes some time till the exception arrives there, because it is noted with garbage collector.
Generally do not use 'async void', but in UI event handlers you have to, so this is thy only way..
This question is old; nonetheless, a similar issue now plagues my UWP app. Occasionally I must unwind the call stack by allowing an exception to propagate up it. I need the exception to reach the app's UnhandledException handler, but that wasn't always happening. This issue included the obvious case of throwing on a non-UI thread. It also included a non-obvious case, the causality of which I have yet to pin down, of throwing on the UI thread.
I conjured up the below solution. I catch the exception and then explicitly post it to the synchronization context. Due to the strange aforementioned issue, I must do this even while already running on the current synchronization context. Otherwise, the exception sometimes doesn't reach the UnhandledException handler.
private void Throw( Exception exception )
{
uiContext.Post( arg => throw exception, null );
throw new OperationCanceledException();
}
Try UnobservedTaskException event of TaskScheduler

NServiceBus ITransport events getting current message reference

I'm building some monitoring tooling around NServiceBus, at the moment i'm subscribing to a few events on the ITransport interface:
ITransport Events:
TransportMessageReceived
FailedMessageProcessing
FinishedMessageProcessing
When subscribing to the TransportMessageReceived event I get a reference to the current message in the event args. However when the FinishedMessageProcessing event is raised it doesn't seem to contain a reference to the message that was completed. This is true for the FailedMessageProcessing event which contains the Exception but not the message that caused the exception.
I was wondering if there is some way to get a reference to the message when the FailedMessageProcessing and FinishedMessageProcessing events are raised
Thanks!
For failed messages, you can implement the following interface to get a reference to the message:
public interface IManageMessageFailures
{
void SerializationFailedForMessage(TransportMessage message, Exception e);
void ProcessingAlwaysFailsForMessage(TransportMessage message, Exception e);
void Init(Address address);
}
Please note that if you use this, then you won't be able to use Second Level Retries out of the box.