现在的位置: 首页 > 综合 > 正文

处理ObjectDataSource调用中DAL层中的异常

2012年07月05日 ⁄ 综合 ⁄ 共 1558字 ⁄ 字号 评论关闭

如题,GridView+ObjectDataSource的模式对一些简单的数据的删改查是相当方便的,但是一直困扰我的是,update和delete的时候,万一从数据访问层抛了异常出来怎么办,因为你并没有写后台代码,而是在前台给了几个参数就完成了所有的事,要解决这个问题,是在gridview的rowupdate事件里捕获:

这个Event Handler 的第二个输入参数是一个类型为 GridViewUpdatedEventArgs 的对象,它有三个属性对异常处理有用:

  • Exception — 这是对已抛出的异常的一个引用;如果没有抛出异常,则该属性的值为 null
  • ExceptionHandled — 这是一个 Boolean 类 型的值,它指示该异常是否已在 RowUpdated Event Handler 中得到处理;如果值为 false (默认值),该异常将被重新抛出,漏出到 ASP.NET 运行时
  • KeepInEditMode — 如果设置为 true ,则GridView 的当前编辑 行将保持在编辑模式;如果为false(默认),则 GridView 行将恢复到只读模式

那么,我们的代码应该检测 Exception 是否为 null ,如果不是 null ,则意味着在执行此操作时发生了异常。在这种情况下,我们想要:

  • 在 ExceptionDetails Label 中显示一条用户友好的消息
  • 指示该异常已得到处理
  • 将 GridView 当前行保持在编辑模式

下面的代码实现了上述目标:

protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
if (e.Exception != null)
{
// Display a user-friendly message
ExceptionDetails.Visible = true;
ExceptionDetails.Text = "There was a problem updating the product. ";

if (e.Exception.InnerException != null)
{
Exception inner = e.Exception.InnerException;

if (inner is System.Data.Common.DbException)
ExceptionDetails.Text +=
"Our database is currently experiencing problems." +
"Please try again later.";
else if (inner is NoNullAllowedException)
ExceptionDetails.Text +=
"There are one or more required fields that are missing.";
else if (inner is ArgumentException)
{
string paramName = ((ArgumentException)inner).ParamName;
ExceptionDetails.Text +=
string.Concat("The ", paramName, " value is illegal.");
}
else if (inner is ApplicationException)
ExceptionDetails.Text += inner.Message;
}

// Indicate that the exception has been handled
e.ExceptionHandled = true;

// Keep the row in edit mode
e.KeepInEditMode = true;
}
}
 
来源链接:http://hi.baidu.com/my534/blog/item/e0d331d802a4c03e32fa1c1b.html

抱歉!评论已关闭.