【问题标题】:Exception handling - Is there a better way?异常处理 - 有没有更好的方法?
【发布时间】:2010-08-10 09:02:57
【问题描述】:

public bool AddEntity(int parentId, 字符串描述) { 尝试 { _connection.Open(); SqlCommand command = new SqlCommand("INSERT Structure (Path,Description)" + "VALUES(" + GetPath(parentId) + ".GetDescendant(" + GetLastChildPath(parentId, 1) + ", NULL), " + 描述 + ")", _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;
        }
    }

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

提前感谢您的帮助。

克莱尔

【问题讨论】:

  • 除了 Rob Stevenson-Leggetts 的回答之外,我还会让 catch-exception 更加具体。例如首先捕获 SqlException,因为这将包含有关实际错误和堆栈跟踪的更多具体信息。将 catch(Exception ex) 保留为最后一个 catch-block。

标签: model-view-controller asp.net-mvc-2 exception-handling


【解决方案1】:

这里有很多问题。

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

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;
    }

【讨论】:

  • +1 用于参数化查询。我知道它存在,但不知道它到底叫什么,或者去哪里看:)
  • 感谢 Rob,快速提问如何处理 SqlException?
【解决方案2】:

您可以利用 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,在这种情况下,将关闭连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 2014-04-14
    相关资源
    最近更新 更多