2017-05-08 165 views
0
BEGIN TRY 
    INSERT INTO [something] ([something], [something]) 
     SELECT 
      [ID] AS OrderNumber, [something], [something] 
     FROM 
      [something] 
     WHERE 
      ID = @OrderNumber 
END TRY 
BEGIN CATCH 
    SELECT 
     ERROR_NUMBER() AS ErrorNumber, 
     ERROR_SEVERITY() AS ErrorSeverity, 
     ERROR_STATE() AS ErrorState, 
     ERROR_PROCEDURE() AS ErrorProcedure, 
     ERROR_LINE() AS ErrorLine, 
     ERROR_MESSAGE() AS ErrorMessage; 
END CATCH 

我发现这样的例外,但我不知道如何在我的网页中显示该错误消息。如果我离开它就像这个代码走低谷,即使我故意弄错了数据。Sql尝试抓住在asp.net

回答

4

如果您不需要例外您的存储过程中处理,那么你并不需要一个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