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


    如题,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
  • 相关阅读:
    《图解HTTP》简单的HTTP协议
    《图解HTTP》web及网络基础
    尚硅谷--雷丰阳--ElasticSearch 7.4.2版本 -- 有道云笔记
    ElasticSearch _bulk批量插入报错
    SpringBoot利用Filter来解决跨域问题
    js中数组的常用方法
    Mysql时间加减函数
    mybatis映射文件中不能使用">""<""&"问题
    博客园样式第二版
    GO学习笔记之 map
  • 原文地址:https://www.cnblogs.com/walkerwang/p/1882709.html
Copyright © 2020-2023  润新知