How to display an error message for a GUI application from non-GUI classes?

I know that I can use something like MessageBox.Show("some error"), but I'm talking about an error that occurs at some lower level in my code that does not have a business throwing a MessageBox or any other GUI elements.

I am creating an RSS client, and I have a class that manages various feeds (say, FeedManager), which is just a wrapper for the list at the moment. Now this class calls another class to access the data. Therefore, at any time when someone from the GUI wants to save the feeds, the GUI just calls FeedManager.SaveFeeds(), which processes the channels and saves them to a file, database, etc. So I try to save the file and something bad happens (either something I encoded or excluded). So now I’m at least 3 levels, GUIFeedManagerSomeDataAccessLayer, and I want to display a message to the user, for example: “Hey, this file was not found” or “You don’t know”, t have permission to write to this place " etc.

How should I do it? A surge MessageBoxfrom the data access layer visually connects this component with a graphical interface. All methods returning lines with error messages also seem silly.

+3
source share
4 answers

Non-GUI code really shouldn't show a MessageBox.

The standard approach is to throw an exception.

Your GUI should surround the call SaveFiles()with a try / catch block and take appropriate action, for example, to show Messagebox.

You may have overlooked that this is exactly what the exceptions are for: for linking errors over (several) method calls.

+2
source

, , , ( ) , , . GUI .. , ,

0

0

, string , ( ), .

GUI, , , ( ).

namespace XXX {
  public delegate void Error(string a_sErrorMessage);

  public class XXX {

    public event Error OnError;

    public void Test() {

      try {
        // Do something
      } catch (Exception ex) {
        // Trigger the event
        OnError(ex.Message);
      }
    }
  }
}
0

All Articles