如果您不需要例外您的存儲過程中處理,那麼你並不需要一個try/catch。你可以讓你的程序拋出錯誤。
在應用程序代碼,您可以趕上SqlException
try
// whatever
catch sqlException as SqlException
// Now you have access to the properties of the SqlException
end try
雖然我沒有表現出任何細節的網頁上的用戶。也許他們需要的只是知道有一個錯誤。他們可能不想或不需要更多。在告訴用戶更多的安全風險方面,他們需要了解幕後的內容。
也許你確實需要SQL中的try/catch,以便回滾事務。
在SQL Server 2012中,你可以做到這一點 - 只是重新拋出原來的錯誤。
begin catch
-- Roll back transaction if needed
throw
end catch
在SQL Server 2012之前,你可以做這樣的事情,這不是很好。或者你可以設置一些輸出參數。麻煩的是,您可以訪問錯誤的詳細信息,但不能重新拋出原始錯誤。
begin catch
declare
@error_number int = error_number(),
@error_severity int = error_severity(),
@error_state int = error_state(),
@error_procedure varchar(255) = error_procedure(),
@error_line int = error_line(),
@error_message varchar(1000) = error_message()
-- Roll back transaction if needed
-- Raise an error with the information from the original error.
RAISERROR (N'Error number %d, severity %d, state %d, procedure %s, line %d, message: %s', @error_severity, @error_state,-- Message text.
@error_number, @error_severity, @error_state, @error_procedure, @error_line, @error_message); -- Second argument.
end catch