2

I'm making my first "real" C# program and I'm thinking about where I should define error messages? Should I do something like this:

static class Error
{
    public static string Example { get { return "Example Error"; } }
}

I could also use values here instead of properties but that would still mean I can't do something like this:

public static string FailedToParse(string filepath, string exmessage)
{
    return ("Failed to parse " + filepath + ".\n" + exmessage);
}

So, is that a good idea? Should I make a new class and write a method for each error? How do you guys implement this and why?

I already read

  1. In C#, what's the best way to store a group of constants that my program uses?
  2. The right way to use Globals Constants
Community
  • 1
  • 1
biepbiep
  • 207
  • 2
  • 11

1 Answers1

1

I think this is something everything should figure out by themselves.

One like to display nice messages to users another just throw those default generated ones.

Personally I like to have codes for errors.

Something like this:

I create a static class called ExceptionFactory and just pass the code to the method called RaiseException.

public static class ExceptionRegions
{
  public static int Internet = 0xA;
  public static int FileSystem = 0xB;
}

public class InternetConnectionException : Exception
{
  public InternetConnectionException () : base("No internet connection available") { }
}

public class FileSystemAccessException : Exception
{
  public FileSystemAccessException () : base("Access to specified path caused an error") { }
}

public static class ExceptionFactory
{
  public static void RaiseException(int code)
  {
    switch(code)
    {
      case ExceptionRegions.Internet : throw new InternetConnectionException();
      ...
      ...
    }
  }
}

Btw, this is a well known pattern called Factory Pattern. :)

Why I like this, because it allows me to set regions in my application. Usually an application has many interfaces such as file system, or web services, or database and all I need to do is create a code for each area and the factory will throw a nice message to user without exposing to the user name of database and number of code line or whatever the default generated error message looks alike.

dev hedgehog
  • 8,698
  • 3
  • 28
  • 55