0

In my user interface (UI) layer (WinForms/WPF), I am using a method from the business layer that accepts some input and creates an object that will be displayed in the UI. The code in the business layer may throw a general or specific exception, which will be handled and result in a null object being returned.

My question is, how can I pass error messages thrown in the business layer to the UI layer in a clean and efficient way? For example, if an exception is thrown in the business layer method, I want to get the error message and display it in the UI.

UI Layer

var configs = RuleConfigurations.CreateInstance(template, "C", "D");

Business Layer

  public static RuleConfigurations CreateInstance(string excelFileName, string fieldColName, string valueColName)
  {
     RuleConfigurations configs = null;
     try
     {
        configs = new RuleConfigurations(excelFileName, fieldColName, valueColName);
     }
     catch (DuplicateNameException e)
     {
        Console.WriteLine(e);
     }
     catch (Exception e)
     {
        Console.WriteLine(e);
     }

     return configs;
  }
Vahid
  • 5,144
  • 13
  • 70
  • 146
  • `catch (Exception e) { Console.WriteLine(e); throw; } ` is going to throw an exception out to your `ui` layer, not return `null`. If you want to pass the exception message to the `ui` layer, why not add an ExceptionMessage property to your RuleConfigurations object and then set that on exception and pass the object to the `ui` layer and display this message via the object property? – Ryan Wilson Apr 23 '20 at 17:40
  • @RyanWilson Sorry, removed it. – Vahid Apr 23 '20 at 17:42
  • No problem. Just making sure you saw that. Would have caused some problematic behavior. Please read the edited version of my previous comment. – Ryan Wilson Apr 23 '20 at 17:43
  • @RyanWilson Good idea. But what if I do not have access to RuleConfigurations class? – Vahid Apr 23 '20 at 17:43
  • You do have access to the business logic and ui layers correct? You could create a new class to hold an instance of RuleConfigurations as well as a string for the exception message. If the exception message is null then you got an initialized RuleConfigurations object else you have an exception. – Ryan Wilson Apr 23 '20 at 17:46
  • In this imaginary case, yes. But there are times when a third-party library handles the exceptions inside its classes and returns a null object like the above example. Then I do not know how to show those messages. – Vahid Apr 23 '20 at 17:53
  • If the 3rd party is catching a suppressing the exceptions, I don't really see any way to get them. – Ryan Wilson Apr 23 '20 at 18:20

0 Answers0