2013-10-27 76 views
1

我正在做我的第一個「真正的」C#程序,我在想我應該在哪裏定義錯誤消息?我應該做這樣的事情:哪裏可以定義錯誤消息

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

我也可以在這裏使用值,而不是性能而是仍然意味着我不能做這樣的事情:

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

所以,是一個很好的理念?我應該爲每個錯誤創建一個新類並寫一個方法嗎?你們如何實現這一點,爲什麼?

我已經讀過

  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

回答

1

我想這是一切都應該自己弄清楚。

一個喜歡向用戶顯示好消息的人只是拋出那些默認生成的消息。

我個人喜歡有錯誤代碼。

事情是這樣的:

我創建了一個名爲ExceptionFactory,只是通過代碼來叫的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(); 
     ... 
     ... 
    } 
    } 
} 

順便說一句,這是一個衆所周知的稱爲工廠模式的模式。 :)

爲什麼我喜歡這個,因爲它允許我在我的應用程序中設置區域。 通常應用程序有許多接口,如文件系統,Web服務或數據庫,我需要做的就是爲每個區域創建一個代碼,工廠會向用戶發出一條好消息,而不會暴露給數據庫的用戶名代碼行數或默認生成的錯誤消息看起來相似。