アプリケーションに次のレイヤーがあります。
- エンティティ
- データベース (エンティティ参照あり)
- ビジネス (データベースとエンティティの参照あり)
- ユーザー インターフェイス (ビジネスとエンティティの参照を含む)
これが私のコードの例です:
- データベース層の UserDAL クラス:
public class UsersDal
{
databaseDataContext db;
public UsersDal()
{
try
{
db = new databaseDataContext(ConnectToDatabase.GetConnectionString());
}
catch (Exception ex)
{
throw ex;
}
}
public List<User> GetAllUsers()
{
try
{
return (from u in db.Users select u).ToList();
}
catch (Exception ex)
{
throw ex;
}
}
等々...
ビジネス層の UserBLL クラスでは、次のように記述します。
public class UsersBll
{
UsersDal user;
public UsersBll()
{
try
{
user = new UsersDal();
}
catch(Exception ex)
{
throw new ProjectException(Errors.CannotCreateObject, ex);
}
}
public List<User> GetAllUsers()
{
try
{
return user.GetAllUsers();
}
catch(Exception ex)
{
throw new ProjectException(Errors.CannotReadData, ex);
}
}
そしてUIで私は書きます:
private void GetUsers()
{
try
{
UsersBll u = new UsersBll();
datagrid.DataSource = u.GetAllUsers();
}
catch(ProjectException ex)
{
MessageBox(ex.UserMessage);// and also can show ex.InnerException.Message for more info
}
}
さて、私は ProjectException という名前のクラスを使用して、私が作成した BLL メッセージと、OS が自動的に操作する例外メッセージを含むエラーを生成します。また、可能性のあるエラーの列挙を作成し、ここに辞書を作成して、それに関する詳細を示します。
namespace Entities
{
public enum Errors
{
CannotCreateObject,
CannotReadData,
CannotAdd,
CannotEdit,
CannotDelete,...
}
[global::System.Serializable]
public class ProjectException : Exception
{
public ProjectException(Errors er, Exception ex)
: base(errors[er], ex)
{
currentEx = er;//er is Errors enum
}
static ProjectException()
{
errors = new Dictionary<Errors, string>();
errors.Add(Errors.CannotCreateObject, "the application cannot connect to database!");
errors.Add(Errors.CannotReadData, "the application cannot read data from database"); //...
}
public string UserMessage
{
get
{
try
{
return errors[currentEx];
}
catch
{
return "Unknown error!";
}
}
}
これでいいですか?それは私にとってはうまくいきます。あなたの考えは何ですか?