通常的方法是在您的 .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, @msgtext=@l_error, @replace='replace'
RAISERROR(50001, 16, 1)
50001 表示将在SqlException.Number 中的错误号。