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

时间:2010-08-10 09:02:58

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

public bool AddEntity(int parentId,string description)         {             尝试             {                 _connection.Open();                 SqlCommand command = new SqlCommand(“INSERT Structure(Path,Description)”+                                                     “VALUES(”+ GetPath(parentId)+“。GetDescendant(”+ GetLastChildPath(parentId,1)+“,NULL),”+                                                     description +“)”,_ connectction);

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

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

提前感谢您的帮助。

克莱尔

2 个答案:

答案 0 :(得分:3)

这里有很多不妥之处。

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

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

 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 :(得分: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();
}

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