bluebit
bluebit

Reputation:

How can I handle and communicate low level errors to wpf gui?

I have a WPF gui that has an instance of a class called Manager, which essentially manages certain communication and data functions.

I have try/catch blocks in my Manager, but I would like to know the best practice to communicate this to the GUI.

For example, clicking a button generates an onClick event, and in that code I would call Manager.DoProcessing(). Trouble is, how do I know if DoProcessing bombed out? I don't want to surround the function call with another try catch...

Would it be sufficient to return my own ErrorType enum which identifies the error:

enum ErrorType
{
NoError, TimeOut, DBCorrupt
}

etc. Or is this simplistic? It should be added that the calls to Manager will be threaded with a BackgroundWorker...

Upvotes: 0

Views: 167

Answers (1)

Rob Fonseca-Ensor
Rob Fonseca-Ensor

Reputation: 15621

Don't return error codes. C# is better than that. Pretty soon you'll have a method that needs to return something: public Person GetPerson(int personID){} and you don't want to have to start working with out parameters. If GetPerson can't "Get" a "Person", that's exceptional, therefore you should throw an exception.

Is your Manager class a ViewModel? If not, wrap it in one. Your viewmodel should catch the exception (whatever thread it occurs on), and take responsibility for presenting it to the view. One option is to create an ObservableCollection of ErrorMessages (or strings, but I would write an ErrorMessage class with message, severity, time of occurance etc). Then your XAML can bind straight to that. Whenever your catch block adds an ErrorMessage to the collection, your view will update itself.

If you are using a BackgroundWorker, then maybe you'll need to check for exceptions in the RunWorkerCompleted event instead of using a 'catch' block. This documentation explains how.

Upvotes: 1

Related Questions