My goal is to catch errors from backup jobs into monitoring table.
The problem is, that there are cases that backup statement returns more than one error, so ERROR_MESSAGE() is not enough:
Msg 3201, Level 16, State 1, Line 1 Cannot open backup device '…'
Operating system error 3(The system cannot find the path specified.).Msg 3013, Level 16, State 1, Line 1 BACKUP DATABASE is terminating
abnormally.
I can use throw to catch both messages, but is there an easy way to insert throw output into table or overcome this problem in another way?
Best Answer
You can enhance error handling with Extended Events to overcome the TRY...CATCH shortcoming you are experiencing. The design pattern involves these steps:
sqlserver.error_reported
events, filtered primarily by SPID.TRY
block.CATCH
block, read the XEvents session data.Here's an example that can be run manually in a single batch from SSMS. Just make sure to replace all occurrences of "2016" in the script with your SPID.
After running the script, your SSMS output should look similar to this:
There's a lot of moving parts there. But you might be able to make it work for you. I wrote a few related blog posts about TRY...CATCH that may be helpful:
The Unfulfilled Promise of TRY...CATCH
Enhanced T-SQL Error Handling With Extended Events
Part 2: Enhanced T-SQL Error Handling With Extended Events