What is best practice to handle all Exceptions in WPF application? - wpf

Is there any way to handle all Errors Exceptions and crashes in WPF application?
I know about DispatcherUnhandledException, but it handles only exceptions in UI thread, doesn't it?
Is there a way to catch and log all exceptions in other threads and binding errors too?

AppDomain.CurrentDomain.UnhandledException
Will catch any unhandled exceptions for the current thread. This is how we handle it in our application.
BindingErrors are always handled and logged to the output window. Before a release we check the output window for binding errors and fix as many as we can.
However it is my opinion that you would not want to treat binding errors as unhandled as they mostly recoverable and should be fixed as best you can before each release. You can change Debug > Exeptions in Visual Studio to make it throw BindingFailure to get more specific information.

Yes, there are 3 places:
place Application.Run() into try ... catch
DispatcherUnhandledException
AppDomain.CurrentDomain.UnhandledException
In either case you should display a please-forgive-me message and suggest to send an error report.
The service on your server should answer either 'thank you for submitting error report' or 'the problem is already fixed in the next version. please update'

Keep in mind, that Microsoft does not recommend catching all exceptions, instead they recommend to catch only exceptions you know (or expect to happen in some place). Even more if you want to get "Certified for Microsoft [Windows|Vista]" logo, you must not catch unknown exceptions, and such exceptions must go to Wer.

Here a nice solution logging with NLog :
Logging in .NET with NLog (default config file, catch all exceptions and route to logger, ...)

Related

Silverlight Exception Message is different on other machines

I am currently stuck with the following problem and running desperately out of ideas, any clues are welcome!
We are using a custom built framework that loads what we call "pages" on demand for the UI, each of these "pages" is a self contained Silverlight XAML that is loaded on demand via:
XamlReader.Load(somePageXamlFile)
It may happen that a part inside this xaml is outdated, so a try / catch block ensures that a XAMLParseException is caught and the respective error handled.
Our current error handling is heavily based on the message of the exception, e.g. we expect a message like this:
"The type 'someType' could not be found. [Line: x Position: y]"
-> we parse the message string and replace the essential xaml parts with custom logic to make it valid again and display info for administrators.
The problem:
Some test machines throw the same exception, but with a different message!
Errormessage there:
"Error 2502 An error has occured."
This breaks our "safety net" logic for this case and currently we can not figure out any reason for this.
Solutions or proposals are very welcome,
thanks in advance!
-Steve
After long and hard search we came down to the following: The clients and the development machines seem to have different versions of the Microsoft agcore.dll (development machines have 2 different version in different paths). As this is the core of the exception we suppose this is the reason for the different error message - we were unable to fix this issue however (we cannot be sure what dll our clients get during SL5 download...) therefore we decided to rewrite the whole code segment to not make use of the exception message text at all. Lesson learned.
Thanks for the feedback. -Steve

How do I use Error Handling Application Block for WPF Unhandled Exceptions?

After I catch an unhandled exception via Application.DispatcherUnhandledException or AppDomain.CurrentDomain.UnhandledException, how should I use the Enterprise Library Error Handling Application Block to do the handling? Can anyone demonstrate some sample code, etc?
How can the end-user easily send the exception details back to developers?
Basically, I'm looking for some guidance on what best practice is after the unhandled error is caught.
"Enterprise Library" allows you to create exception handling policies as per the CLR Type of the error. You can use the DispatcherUnhandledException and UnhandledException types for the same.

How to return warnings from server side to silverlight

We have a business case that need to return both validation errors and warings from server side and display on silverlight.
I see the silverlight is using System.ComponentModel.DataAnnotations.ValidationResult to process errors. It does not contain and fields for "warnings".
I am wondering if anybody has a good idea to handle this problem. Thanks.
I think ValidationResult is used by ValidationException which is thrown by the subclasses of ValidationAttribute. Normally this mecanism is used with blocking validation errors because throwing to exception stops execution of the code. If it happens in your service, the exception can be sent to the client and processessed, but this is not always a wanted scenario.
You could extend this model (those classes ValidationAttribute, its subclasses, ValidationException are not sealed) to add a warning flag but then you'd have to trap the exception to continue the processing and rethrow in case of a warning.
Another alternative is to add business logic validation errors and warnings to your response to the client. I like this approach because you can then include whatever info you want the way you want/need it.

On Silverlight initialization, what exception to throw?

What's the best exception to throw if a Silverlight app fails initialization or fails to load?
Or should I not throw an exception at all?
In my experience, load/initialization failure sometimes results in a managed exception, sometimes not. In some cases, the exception or failed condition may only be accessible at the client through javascript. In the event of an exception that comes from the entire app failing, there should be some indication to the user that the app failed completely.
You should consume and handle exceptions that are thrown from init/load failure. Explicit throwing of exceptions should be reserved for conditions where there is a violation of business logic, communcations failure, or other truly exceptional case.
I personally don't like the UI that IE shows when a Silverlight application throws an unhandled exception. It has a very small window that shows the exception text but the options present certainly aren't user friendly. I guess this is a matter of opinion, but my preference is to catch any exceptions during initialization and try to present the user with a meaningful description of what happened. Typically I store some settings in isolated storage, so one helpful message might describe how to clear the iso store for my app to eliminate some sort of configuration problem. As long as you can provide the user with some meaningful steps to fix the problem, or at least who to contact if they can't, I'd say it's better not to throw exceptions during initialization that would cause the app to fail to load.

Where should exceptions be caught and handled in a WPF application?

We have exception catching code in most of our event handlers etc, this leads to very complex logic, with flags that are set to say if there has been an exception so as not do the next step etc.
At first sight I would move all exception report/logging to the AppDomain.UnhandledException event, however from my experience with WinForms this will lead to a lot of exceptions being lost.
Also when there is an exception we have include details of the operation the user was trying to do in the log message.
So what are people experiences both bad and good at exception logging/reporting/recovering in WCF applications?
(I would love to say that we had something like the Model-View ViewModel (MVVM) pattern) in use, but we don’t and are a long way from being able to use any “clean” design like that)
Its not specific to WPF, but the best place to handle exceptions is to handle them at the point where user interaction with the form is converted into a logic process. This is either in the codebehind or in a controller method.
Only at this level do you know what the user is trying to do and what reasonable steps to take when an exceptional situation is encountered.
Of course, if you don't know what exceptions may be thrown don't try to handle them. And don't bother handling exceptions that you can't do anything about.
You should never have to use flags to say exceptions have been handled - that smells like bad design.
Exceptions fall into two categories:
expected (e.g. validation failed, data could not be put into database)
unexpected
your expected ones should be handled pretty quickly, and logged depending on the type of exception. For instance, if the user entered some data that was rejected by validation code in the business layer, i would catch the exception and notify the user, but not log it - because it was expected and i can deal with it. Others could be "expected", but you cannot deal with it - like a WCF call failed due to timeout or oversized data packet. This you should definately log - you may even be able to recover from it, so once again it should be caught and dealt with. Note the lack of flags - an exception is either dealt with, or it continues to bubble up. If you need to take an action you can do so, and then rethrow the exception to let it bubble up further - look, still no flags :)
Another approach i have taken in the past when throwing (custom) expected exceptions in an ASP.NET application is to mark it as being capable of being handled locally or not. This means that when the aspx caught the error (generic error handler in a base page that all apsx's inherited from), then it knew whether it should just show it locally within the page (after doing a text lookup in a resource file), or whether it should redirect to an error page. This approach was especially useful when doing a mixture of standard postbacks and ajax callbacks (may not be particularly useful to WPF apps though).
For major unexpected errors, you can catch those at the Application level, here is a previous SO post about it. Another two related posts that might be useful here, and here.
Another thing i should mention is to make sure your error logging is relatively bulletproof - there is nothing worse than your exception logging process throwing an exception, and losing all the valuable details of that tricky bug you are trying to track down for that irate user.

Resources