正常情況下,它的方法是在.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