异常处理 - 有没有更好的方法?
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;
}
}
在上面的例子中是否有更好的方法来处理异常?
在此先感谢您的帮助。
克莱尔
这里有很多错误。
a。您正在使用内联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;
}
用于参数化查询。我知道这是存在的,但不知道它叫什么,或者看看:) – 2010-08-10 09:22:19
感谢这个Rob,快速的问题我该如何处理SqlException? – ClareBear 2010-08-10 13:09:56
您可以利用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();
}
在这种情况下,将关闭连接。
除了Rob Stevenson-Leggetts的回答,我还会让捕捉异常更具体。例如首先捕获一个SqlException,因为它将包含关于实际错误和堆栈跟踪的更多特定信息。 让catch(Exception ex)作为最后的catch-block。 – 2010-08-10 10:02:04