【问题标题】:Best way to handle error catching处理错误捕获的最佳方法
【发布时间】:2017-11-23 15:34:08
【问题描述】:

我正在创建一个执行一些 SQL 服务器配置的应用程序,它是更大系统的一部分

系统的数据库中有一个配置表如下:

CREATE TABLE Config
(
    ConfigItem NVARCHAR(255) PRIMARY KEY NOT NULL,
    ConfigValue NVARCHAR(255) NOT NULL
)

INSERT INTO Config
VALUES
('LinkedServerName','MYLINKEDSERVER'),
('DatabaseName','APPLICATIONDATABASE')

我的应用是一个带有两个文本框和一个按钮的 Windows 窗体。该表单还有一个初始空白标签,用于向用户显示错误消息。

在第一个文本框中显示链接服务器名称的值,在第二个文本框中显示数据库的值。两者都在表单加载时显示。

点击提交按钮后,数据库中的两个值会根据文本框中的内容进行更新。

我有以下代码在表单加载时用当前值填充两个文本框:

    private void Form1_Load(object sender, EventArgs e)
    {
        // populate the textboxes
        txtLinkedServer.Text = GetConfigValue("LinkedServerName");
        txtDatabase.Text = GetConfigValue("DatabaseName");
    }

    private string GetConfigValue(string ConfigItem)
    {
        // get the value for the given config item from the database
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            DataTable dt = new DataTable();
            SqlCommand com = new SqlCommand();
            com.CommandText = "SELECT ConfigValue FROM Config WHERE ConfigItem = @ConfigItem";
            com.Parameters.AddWithValue("ConfigItem", ConfigItem);
            com.Connection = conn;

            try
            {
                conn.Open();
                dt.Load(com.ExecuteReader());

                if (dt.Rows.Count == 0)
                {
                    return "Error retrieving " + ConfigItem + " name from config table";
                }
                else
                {
                    return dt.Rows[0]["ConfigValue"].ToString();
                }
            }
            catch
            {
                return "Error in GetConfigValueMethod when retrieving " + ConfigItem;
            }
            finally
            {
                conn.Close();
            }
        }
    }

如果检索配置数据时出现问题(由 GetConfigValue 中的 catch 块捕获),我希望标签显示从 GetConfigValue 返回的字符串。

最好/最简洁的方法是什么?我在想

private void Form1_Load(object sender, EventArgs e)
{
    string message;
    // populate the textboxes
    try
    {
         message = GetConfigValue("LinkedServerName");
         txtLinkedServer.Text = message
    }
    catch
    {
         lblFeedback.Text = message;
    }
    // do the same for the database here
}

但是,我不能这样做

使用未分配的局部变量“消息”

或者我最好更改 GetConfigValue 方法,以便它在 catch 块中抛出它自己的异常,而不是返回一个字符串并在 Load 方法中捕获它,如下所示;

private string GetConfigValue(string ConfigItem)    
{
    // get the value for the given config item from the database
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
             // same code here

        try
        {
            // same code here
        }
        catch
        {
            Throw new Exception ("Error in GetConfigValueMethod when retrieving " + ConfigItem);
        }
        finally
        {
            conn.Close();
        }
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    // populate the textboxes
    try
    {
         txtLinkedServer.Text = GetConfigValue("LinkedServerName");

    }
    catch (Exception e)
    {
         lblFeedback.Text = e.Message;
    }
    // do the same for the database here
}

或者完全是其他方式?

【问题讨论】:

  • 尝试string message = null;避免编译错误。

标签: c# sql-server error-handling ado.net


【解决方案1】:

看看你的第二个例子,如果这是你想要的结果,那么看起来你只需要替换

catch
{
     lblFeedback.Text = message;
}

在你的第一个例子中

catch (Exception e)
{
     lblFeedback.Text = e.Message;
}

来自您的第二个示例。

【讨论】:

    【解决方案2】:

    正如错误消息所说,您尝试使用未分配的变量“消息”,因此您遇到了该错误。

    试试这个:

    private void Form1_Load(object sender, EventArgs e)
    {
    string message = String.Empty;
    // populate the textboxes
    try
    {
         message = GetConfigValue("LinkedServerName");
         txtLinkedServer.Text = message
    }
    catch (Exception ex)
    {
         if (!String.IsNullOrEmpty(message))
            lblFeedback.Text = message;
         else
            lblFeedback.Text = ex.Message;
    
    }
    // do the same for the database here
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-12
      • 2016-08-21
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多