SQL Server › Error Handling with TRY CATCH
How would you build a centralized, reusable error logging procedure that captures detailed error information whenever it is called from within a CATCH block?
AdvancedAnswer
You create a stored procedure that accepts the standard error information as parameters, or calls the error functions directly since they remain accessible within the scope of the calling CATCH block, and inserts that information into a dedicated error log table, giving you a consistent record of every error across your entire application for later analysis.
CREATE PROCEDURE LogError
AS
BEGIN
INSERT INTO ErrorLog (ErrorNumber, ErrorMessage, ErrorDate)
VALUES (ERROR_NUMBER(), ERROR_MESSAGE(), GETDATE());
END;
-- Usage inside a CATCH block
BEGIN CATCH
EXEC LogError;
END CATCH;Real-world example A large application calls a shared LogError procedure from every CATCH block across dozens of stored procedures, building a single centralized error log table that makes it much easier to spot recurring problems.