How to handle errors in user function in MS SQL Server? try...catch is not allowed in it, but what should I do?

  • 3
    Return the result from the function that would signal an error. - cpp_user
  • What kind of errors are you going to handle inside the function? What should happen in the body of the function to generate a runtime error? Give a specific example. - pegoopik

1 answer 1

Raise error will not work. But! You can make a special mistake. For example, make SELECT CAST ('<Message_ Marker> Message' AS Int), which will result in a CAST error. And already above the level where the error is caught to process the following message:

Conversion failed when converting the varchar value '<Message_ Marker> Message' to data type int.

Naturally, you will have to cut the original message and make RaisError again with the original message.

If you have a standard error handling procedure and are used in all (!) CATCHs, then this approach may well work.