CAD*_*CAD 1 .net c# mvp exception-handling
在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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑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");
}
}
Run Code Online (Sandbox Code Playgroud)
BankAccountPresenter
private void SaveBankAccount()
{
try
{
_DataService.InsertAccount(_model);
}
catch (Exception e) { MessagingService.ShowErrorMessage(e.Message); }
}
Run Code Online (Sandbox Code Playgroud)
为什么我在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 }
Run Code Online (Sandbox Code Playgroud)
然后catch (Exception e) { MessageBox.Show(("Error: " + e.Message)); }在更高级别处理它().
回复EDIT2:
没关系.但是,您当前的实现会将"实际"异常及其堆栈跟踪抛出到bin中,以支持您的有用消息.您需要将其添加为内部异常,如下所示:
catch(Exception e){
throw new Exception("some helpful message", e);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1602 次 |
| 最近记录: |