【问题标题】:How to log SqlDataAdapter exceptions asynchronously?如何异步记录 SqlDataAdapter 异常?
【发布时间】:2023-03-09 16:29:01
【问题描述】:

我有 ASP.NET MVC 应用程序,并且正在使用 SqlDataAdapter 来处理 sql server 方法。下面的方法在发生异常时什么都不返回,所以当sql server命令出错时我没有任何信息。

public int ExecuteNonQuery(string pSql, List<SqlParameter> prm)
    {
        SqlCommand cmd = new SqlCommand(pSql, sqlConnection);
        int result = 0;

        if (sqlConnection.State == ConnectionState.Closed)
        {
            sqlConnection.Open();
        }

        try
        {

            cmd.Parameters.AddRange(prm.ToArray());

            result = cmd.ExecuteNonQuery();


            return result;
        }
        catch (Exception ex)
        {
            return 0;
        }
        finally
        {
            sqlConnection.Close();
        }
    }

如何在不影响用户体验的情况下异步记录异常?另外,我想将其记录到数据库中,如果出现超时异常,那么记录此超时可能会在记录时再次超时。

【问题讨论】:

    标签: sql-server asp.net-mvc asynchronous logging sqldataadapter


    【解决方案1】:

    您的示例中没有 SqlDataAdapter 代码。话虽如此,您可以使用three DataAdapter events 来响应对数据源中的数据所做的更改。

    行更新行更新,& FillError

    还有一个:

    Status 属性来确定在 操作,并在需要时控制针对当前的操作 和结果行。

    当出现错误时,您可以在这些事件中异步记录异常。

    Examples from MSDN:

    protected static void OnRowUpdated(
      object sender, SqlRowUpdatedEventArgs args)
    {
      if (args.Status == UpdateStatus.ErrorsOccurred)
      {
        args.Row.RowError = args.Errors.Message;
        args.Status = UpdateStatus.SkipCurrentRow;
    
        Task.Run(() => LogError());
      }
    }
    
    protected static void FillError(object sender, FillErrorEventArgs args)
    {
      if (args.Errors.GetType() == typeof(System.OverflowException))
      {
        // Code to handle precision loss.
        //Add a row to table using the values from the first two columns.
        DataRow myRow = args.DataTable.Rows.Add(new object[]
           {args.Values[0], args.Values[1], DBNull.Value});
        //Set the RowError containing the value for the third column.
        args.RowError = 
           "OverflowException Encountered. Value from data source: " +
           args.Values[2];
        args.Continue = true;
    
        Task.Run(() => LogError());
      }
    }
    
    private void LogError()
    {
        // logging code
    }
    

    【讨论】:

    • 谢谢,但我不知道如何登录 anysc。这就是我实际上要问的。
    • @doganhisa 我已经更新了我的答案。最简单的方法是创建一个任务。
    猜你喜欢
    • 2014-02-28
    • 2013-06-05
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多