gpt4 book ai didi

c# - DAL 中的异常处理

转载 作者:太空宇宙 更新时间:2023-11-03 20:05:01 27 4
gpt4 key购买 nike

在 MVP winforms 应用程序中,我在 DAL 中按如下方式处理异常。

由于用户消息传递不是 DAL 的责任,我想将它移到我的 Presentation 类中。

你能告诉我一个标准的方法吗?

    public bool InsertAccount(IBankAccount ba)
{
string selectStatement = @"IF NOT EXISTS (SELECT ac_no FROM BankAccount WHERE ac_no=@ac_no) BEGIN INSERT INTO BankAccount ...";

using (SqlConnection sqlConnection = new SqlConnection(db.ConnectionString))
{
using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection))
{
try
{
sqlConnection.Open();
sqlCommand.Parameters.Add("@ac_no", SqlDbType.Char).Value = ba.AccountNumber;
//
//

sqlCommand.ExecuteNonQuery();
return true;
}
catch (Exception e) { MessageBox.Show(("Error: " + e.Message)); }
if (sqlConnection.State == System.Data.ConnectionState.Open) sqlConnection.Close();
return false;
}

}
}

编辑2:

所以根据我重新编辑帖子的答案,现在我的异常处理代码看起来像这样......

DAL

public bool InsertAccount(IBankAccount ba)
{
try
{
sqlConnection.Open();
//
}
catch (SqlException)
{
throw new Exception("DataBase related Exception occurred");
}
catch (Exception)
{
throw new Exception("Exception occurred");
}
}

BankAccountPresenter

    private void SaveBankAccount()
{
try
{
_DataService.InsertAccount(_model);
}
catch (Exception e) { MessagingService.ShowErrorMessage(e.Message); }
}

我在 DAL 中捕获异常的原因是,即使目前我没有记录错误,但我将来可能不得不这样做。

而且通过这种方式我可以区分 DAL 中的错误消息,无论是与 sql 相关的还是一般的。

在显示错误消息时,我在演示者中使用了消息传递服务。

这个意思完整吗?这可以简化吗?

最佳答案

您返回 false 以指示出现异常。不建议这样做。

重新抛出

catch(Exception e) {
//blah, maybe add some useful text to e
throw;
}
finally { //close up shop Although, look up what using does first incidentally }

然后在更高层次上处理(catch (Exception e) { MessageBox.Show(("Error: "+ e.Message)); })。

对 EDIT2 的响应:

没关系。但是,您当前的实现会在 bin 中抛出“实际”异常及其堆栈跟踪,以支持您提供有用的消息。您需要像这样将其添加为内部异常:

catch(Exception e){    
throw new Exception("some helpful message", e);
}

关于c# - DAL 中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24205251/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com