code_junkie

How to log a stored procedure error

Nov 11th, 2011
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. IF @@ERROR <> 0 ...
  2.  
  3. DECLARE @ErrorCode INT
  4.  
  5. INSERT INTO Table ...
  6.  
  7. SET @ErrorCode = @@ERROR
  8. IF @ErrorCode <> 0
  9. BEGIN
  10. INSERT INTO ErrorLog (ErrorCode, Message)
  11. VALUES (@ErrorCode, 'The INSERT operation failed.')
  12. END
  13.  
  14. RAISERROR ... WITH LOG
  15.  
  16. xp_logevent {error_number, 'message'} [, 'severity']
  17.  
  18. ALTER PROCEDURE [dbo].[StoreProcedureName]
  19. (
  20. parameters
  21. )
  22. AS
  23. BEGIN
  24. SET NOCOUNT On
  25. BEGIN TRY
  26. --type your query
  27.  
  28. End Try
  29. BEGIN CATCH
  30. SELECT
  31. ERROR_NUMBER() AS ErrorNumber,
  32. ERROR_SEVERITY() AS ErrorSeverity,
  33. ERROR_STATE() AS ErrorState,
  34. ERROR_PROCEDURE() AS ErrorProcedure,
  35. ERROR_LINE() AS ErrorLine,
  36. ERROR_MESSAGE() AS ErrorMessage
  37. RETURN -1
  38. END CATCH
  39. End
Add Comment
Please, Sign In to add comment