正常情况下,它的方法是在.Net代码中定义错误常量,然后检查异常处理代码中的值。你可以使用常量使代码更易读,这样的事情:
/// <summary>
/// Represents the error code returned from stored procedure when entity could not be found.
/// </summary>
private const int SQL_ERROR_CODE_ENTITY_NOT_FOUND = 50001;
/// <summary>
/// Represents the error code returned from stored procedure when entity to be updated has time mismatch.
/// </summary>
private const int SQL_ERROR_CODE_TIME_MISMATCH = 50002;
/// <summary>
/// Represents the error code returned from stored procedure when a persistence exception occurs (ex.
/// billing flag is invalid, child records exist which prevent a delete, etc.).
/// </summary>
private const int SQL_ERROR_CODE_PERSISTENCE_ERROR = 50003;
然后,您可以处理这样的例外,它使你的代码更具可读性和可维护性:
if (e.InnerException is SqlException)
{
// verify exception code from SP and throw proper exception if required
var sqlException = (SqlException)e.InnerException;
if (sqlException.Number == SQL_ERROR_CODE_ENTITY_NOT_FOUND)
{
e = new EntityNotFoundException(e.Message, e);
}
else if (sqlException.Number == SQL_ERROR_CODE_TIME_MISMATCH)
{
e = new EntityTimestampMismatchException(e.Message, e);
}
else if (sqlException.Number == SQL_ERROR_CODE_PERSISTENCE_ERROR)
{
e = new EntityServicePersistenceException(e.Message, e);
}
}
这在我看来可以做得很干净,但它仍然可以,因为你在一个地方定义了错误代码,所以如果有什么改变,你只需改变一个常量。
,提高了错误,你可以做在T-SQL是这样的:
-- record wasn't found, raise an error
DECLARE @l_error NVARCHAR(1000)
SET @l_error = 'Record with ' + @p_IdFieldName + ' = ' + CONVERT(VARCHAR(128), @p_id)
+ ' does not exist in table [' + @p_TableName + ']'
EXEC sp_addmessage @msgnum=50001, @severity=16, @[email protected]_error, @replace='replace'
RAISERROR(50001, 16, 1)
的50001表示将在SqlException.Number
错误编号。
来源
2010-10-12 14:20:58
dcp
仔细研究一下,看起来现有的代码在SQL代码中使用msg_str来引发错误,而不是msg_id。根据RAISERROR文档“当指定msg_str时,RAISERROR产生错误消息,错误号为50000.”我想我们必须将存储过程中的实现切换为基于ID而不是基于字符串的实现。还看起来我们将不得不使用“sp_addmessage”将错误号预加载到数据库中。 – Jay 2010-10-12 14:30:50
我想dcp是说你不应该定义'msg_str',它可以让'msg_id'成为你想要的东西。 – 2010-10-12 14:34:44
@Jay - Abe是对的,我调用了RAISEERROR的方式,我传递了50001,而不是消息字符串。 – dcp 2010-10-12 14:43:44