3
votes

I know 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 has no business tossing up a MessageBox or any other GUI elements.

I'm building an RSS Client and I have a class which manages the various feeds (lets say FeedManager) which is just a wrapper for a list at this point. Now this class calls on another class for data access. So anytime someone in the GUI wants to save the feeds, the GUI simply calls FeedManager.SaveFeeds() which processes the feeds and saves them to a file, database, etc. So I attempt to save to a file and something bad happens (either something I coded for or an exception). So now I'm at least 3 levels deep, GUI -> FeedManager -> SomeDataAccessLayer, and I want to display a message to the user like "Hey, that file was not found" or "You don't have permission to write to that location", etc...

How should I go about this? Throwing up a MessageBox from the data access layer blatantly couples that component to the GUI. Having all methods return strings with any error messages seems silly as well.

4

4 Answers

2
votes

Non-GUI code should indeed not show a MessageBox.

The standard approach is to throw an Exception.

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

Maybe you overlooked the point is that this is exactly what Exceptions are for: to communicate errors over (multiple) method calls.

0
votes

Perhaps you could create a new class that handles errors, and that class will (depending on your wishes) print it to the console, display it in e.g. a public static GUI component, etc. That way you could decouple it from the GUI in an easy way, but still show messages in it

0
votes

You should throw exception instead of message box

0
votes

My solution for this was to use an event with a string parameter and whenever an exception (or any other error) occurred I triggered the event and past to it the message.

In the GUI class that create the instance just need to register to that event and in case it was triggered pop up a message box (or any other info).

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);
      }
    }
  }
}