异常处理 - 有更好的方法吗?

发布于 2024-09-14 04:16:32 字数 996 浏览 3 评论 0原文

public bool AddEntity(int ParentId, 字符串描述) { 尝试 { _connection.Open(); SqlCommand 命令 = new SqlCommand("INSERT 结构(路径,描述)" + "VALUES(" + GetPath(parentId) + ".GetDescendant(" + GetLastChildPath(parentId, 1) + ", NULL), " + 描述+“)”,_连接);

            if (command.ExecuteNonQuery() <= 0) _success = false;

            command.Connection.Close();

            if (_success)
            {
                return true;
            }

            throw new Exception("An error has occured whilst trying to add a entity");
        }
        catch (Exception ex)
        {
            AddError(new ErrorModel("An error has occured whilst trying to add a entity", ErrorHelper.ErrorTypes.Critical, ex));
            return false;
        }
    }

有没有更好的方法来处理上面示例中的异常?

预先感谢您的任何帮助。

克莱尔

public bool AddEntity(int parentId, string description)
{
try
{
_connection.Open();
SqlCommand command = new SqlCommand("INSERT Structure (Path,Description) " +
"VALUES(" + GetPath(parentId) + ".GetDescendant(" + GetLastChildPath(parentId, 1) + ", NULL), " +
description + ")", _connection);

            if (command.ExecuteNonQuery() <= 0) _success = false;

            command.Connection.Close();

            if (_success)
            {
                return true;
            }

            throw new Exception("An error has occured whilst trying to add a entity");
        }
        catch (Exception ex)
        {
            AddError(new ErrorModel("An error has occured whilst trying to add a entity", ErrorHelper.ErrorTypes.Critical, ex));
            return false;
        }
    }

Is there a better way of handling the exceptions in the example above?

Thanks in advance for any help.

Clare

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

扶醉桌前 2024-09-21 04:16:32

这里有很多问题。

一个。您正在使用内联 SQL 并将我只能假设为用户生成的数据注入其中。这是一个安全风险。使用参数化查询

b.您的异常处理没问题,但是如果发生错误,这将使连接保持打开状态。我会这样写:

 public bool AddEntity(int parentId, string description)
 {
    try
    {
        //Assuming you have a string field called connection string
        using(SqlConnection conn = new SqlConnection(_connectionString))
        {
            SqlParameter descriptionParam = new SqlParameter("@description", SqlDbType.VarChar, 11);
            descriptionParam.Value = description;

            SqlParameter parentIdParam = new SqlParameter("@parentId", SqlDbType.Int, 4);
            parentIdParam.Value = parentId;

            //Bit confused about the GetPath bit.
            SqlCommand command = new SqlCommand("INSERT Structure (Path,Description) " +
                                            "VALUES(" + GetPath(parentId) + ".GetDescendant(" + GetLastChildPath(parentId, 1) + ", NULL),@description)", conn);

            command.Parameters.Add(descriptionParam);

            if (command.ExecuteNonQuery() <= 0) _success = false;
        }

        if (_success)
        {
            return true;
        }

        //This isn't really an exception. You know an error has a occured handle it properly here.
        throw new Exception("An error has occured whilst trying to add a entity");
    }
    catch (Exception ex)
    {
        AddError(new ErrorModel("An error has occured whilst trying to add a entity", ErrorHelper.ErrorTypes.Critical, ex));
        return false;
    }

There's quite a few things wrong here.

a. You're using inline SQL and injecting what I can only assume to be user generated data into it. This is a security risk. Use a parameterised query.

b. You're exception handling is ok but this will leave the connection open if an error occurs. I'd write it like so:

 public bool AddEntity(int parentId, string description)
 {
    try
    {
        //Assuming you have a string field called connection string
        using(SqlConnection conn = new SqlConnection(_connectionString))
        {
            SqlParameter descriptionParam = new SqlParameter("@description", SqlDbType.VarChar, 11);
            descriptionParam.Value = description;

            SqlParameter parentIdParam = new SqlParameter("@parentId", SqlDbType.Int, 4);
            parentIdParam.Value = parentId;

            //Bit confused about the GetPath bit.
            SqlCommand command = new SqlCommand("INSERT Structure (Path,Description) " +
                                            "VALUES(" + GetPath(parentId) + ".GetDescendant(" + GetLastChildPath(parentId, 1) + ", NULL),@description)", conn);

            command.Parameters.Add(descriptionParam);

            if (command.ExecuteNonQuery() <= 0) _success = false;
        }

        if (_success)
        {
            return true;
        }

        //This isn't really an exception. You know an error has a occured handle it properly here.
        throw new Exception("An error has occured whilst trying to add a entity");
    }
    catch (Exception ex)
    {
        AddError(new ErrorModel("An error has occured whilst trying to add a entity", ErrorHelper.ErrorTypes.Critical, ex));
        return false;
    }
时光无声 2024-09-21 04:16:32

您可以利用 IDisposable 接口以及 using 块的强大功能。

using(var connection = new Connection()) // Not sure what _connection is, in this method, so making pseudo-code
{
  // ... work with connection
}

即使抛出异常,这也会关闭连接。它变成(或多或少)这样:

var connection = new Connection();

try
{
  // ... work with connection
}
finally
{
  connection.Dispose();
}

在这种情况下,Dispose 将关闭连接。

You can take advantage of the IDisposable interface, and the power of a using block.

using(var connection = new Connection()) // Not sure what _connection is, in this method, so making pseudo-code
{
  // ... work with connection
}

This will close the connection even if an exception is thrown. It turns into (more-or-less) this:

var connection = new Connection();

try
{
  // ... work with connection
}
finally
{
  connection.Dispose();
}

Dispose, in this case, will close the connection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文