Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

SQL Server ERROR_MESSAGE Function: How to Use It

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The ERROR_MESSAGE() function in SQL Server returns the message text of the error that caused the CATCH block to execute. It is only valid inside a TRY...CATCH construct; outside of that, it returns NULL. To use it, wrap your statements in BEGIN TRY...END TRY and BEGIN CATCH...END CATCH, then call ERROR_MESSAGE() in the CATCH block to capture or log the error text.

What You'll Need

  • Access to a SQL Server instance (any recent version, including Azure SQL Database) with permission to create and run T-SQL batches.
  • A client tool such as SQL Server Management Studio (SSMS) or Azure Data Studio.
  • Basic familiarity with T-SQL batches, BEGIN TRY, and BEGIN CATCH.

Step-by-Step

  1. Open a new query window in SSMS or Azure Data Studio and connect to your database. Make sure you are in the correct database context (for example, USE YourDatabase;) before running the script.
  2. Write a TRY block that contains the statement you expect might fail. For example, a division by zero or an insert that violates a constraint. The TRY block is where normal execution begins.
  3. Add a CATCH block immediately after the TRY block. The CATCH block runs only if an error with severity 11 or higher occurs inside the TRY block.
  4. Inside the CATCH block, call ERROR_MESSAGE() to retrieve the error text. You can SELECT it, insert it into a logging table, or return it to the application. For example:
    BEGIN TRY
        SELECT 1/0;
    END TRY
    BEGIN CATCH
        SELECT ERROR_MESSAGE() AS ErrorText;
    END CATCH;
  5. Run the batch (F5 in SSMS). The result grid will show the error message, such as "Divide by zero error encountered."
  6. Combine ERROR_MESSAGE() with other error functions for a fuller picture: ERROR_NUMBER(), ERROR_SEVERITY(), ERROR_STATE(), ERROR_PROCEDURE(), and ERROR_LINE(). These are also only valid inside the CATCH block.
  7. Log the error to a table if you need a persistent record. Create a simple logging table with columns for the error number, message, severity, and timestamp, then INSERT the values from the CATCH block. Remember that the INSERT itself must be committed; if the transaction is doomed, roll back first.
  8. Test with different error types to see how ERROR_MESSAGE() behaves: a primary key violation, a conversion failure, and a RAISERROR or THROW statement. Note that THROW can re-raise the original error, preserving the message.
  9. Handle transactions carefully. If the error dooms the transaction, use XACT_STATE() in the CATCH block to decide whether to COMMIT or ROLLBACK. ERROR_MESSAGE() still returns the text even after a rollback, as long as you are still inside the CATCH block.
  10. Clean up any test tables or procedures you created, and verify that your production code uses TRY...CATCH where appropriate.

Common Mistakes

  • Calling ERROR_MESSAGE() outside a CATCH block. It returns NULL because there is no active error context. Always use it inside BEGIN CATCH...END CATCH.
  • Assuming it works for all errors. Errors with severity 20 or higher that terminate the connection, and compile-time errors in the same batch, may not be caught by TRY...CATCH. Also, errors that occur during statement recompilation can bypass the CATCH block.
  • Forgetting that the CATCH block does not automatically roll back transactions. If the transaction is uncommittable, you must roll back explicitly; otherwise the session may hold locks.
  • Using ERROR_MESSAGE() after the CATCH block has ended. The error functions are scoped to the CATCH block; once you exit, they return NULL.
  • Overlooking that RAISERROR with severity 11+ inside TRY is caught, but PRINT is not an error. Only actual errors trigger the CATCH block.

Tips

  • Store the error details in a table with a timestamp and the application name or user for easier debugging.
  • Use THROW instead of RAISERROR in new code; THROW is simpler and always uses severity 16 by default, and it preserves the original error message when re-throwing.
  • Keep the CATCH block short; avoid expensive operations that could fail and mask the original error.
  • Test your error handling with deliberate failures, such as inserting a duplicate key or dividing by zero, to confirm the messages are captured as expected.
  • Remember that ERROR_MESSAGE() returns nvarchar(4000); if the message is longer, it may be truncated. Use ERROR_MESSAGE() with care for very long messages.

Troubleshooting

  • ERROR_MESSAGE() returns NULL: Check that you are inside a CATCH block and that the error actually occurred in the TRY block. Also verify that the error severity is 11 or higher; some warnings do not trigger CATCH.
  • The CATCH block is not executed: Ensure the statement is inside BEGIN TRY...END TRY and that the error is not a compile-time error in the same batch (for example, a missing table reference). Move the statement to dynamic SQL if needed.
  • The error message is not the original one: If you use RAISERROR with a custom message, ERROR_MESSAGE() returns that custom text. If you re-throw with THROW, the original message is preserved.
  • Transaction remains open after the CATCH block: Use XACT_STATE() to check if the transaction is committable. If it returns -1, roll back. If it returns 1, you can commit or roll back as appropriate.
  • Permission errors: If you cannot create procedures or tables, ask your DBA for the necessary rights.

Frequently Asked Questions

Can I use ERROR_MESSAGE() outside a TRY...CATCH block?

No. It returns NULL because there is no active error context. It is only valid inside a CATCH block.

Does ERROR_MESSAGE() work with THROW?

Yes. When you use THROW inside a CATCH block without parameters, it re-raises the original error, and ERROR_MESSAGE() in an outer CATCH will return the original message.

What is the difference between ERROR_MESSAGE() and @@ERROR?

@@ERROR returns the error number of the last statement, while ERROR_MESSAGE() returns the message text. @@ERROR is reset after each statement, whereas ERROR_MESSAGE() is scoped to the CATCH block.

Can I capture the error message in a variable?

Yes. Declare a variable of type nvarchar(4000) and assign it: SET @ErrorMessage = ERROR_MESSAGE(); inside the CATCH block.

Does ERROR_MESSAGE() work in Azure SQL Database?

Yes, it behaves the same as in SQL Server on-premises.

Why does ERROR_MESSAGE() return a different message than what I see in SSMS?

SSMS may show additional information like line numbers and procedure names. ERROR_MESSAGE() returns only the message text. Use ERROR_LINE() and ERROR_PROCEDURE() for those details.