October 25, 2007 at 3:33 am
I have a stored procedure that removed and recreates constraints and indexes on a database. I am using try catch blocks to capture any errors to a log and then
reporting these at the end of the execution.
The problem I have found is that ERROR_MESSAGE() and ERROR_NUMBER() only return the last error encountered, so that the message in my error log
only reads Could not create constraint. See previous errors. Not very helpful!
Running the failed command on its own would generate a error message
Msg 2714, Level 16, State 4, Line 1
There is already an object named 'my_constraint_name' in the database.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
Now the first message returned is helpful, it tells me why the command has failed, and not just the fact it has failed.
What I am struggling to do is find a way to get that first meaningful message into my error log rather than the less useful second message, which seems to be the default. Is there a way of doing it ?
September 14, 2009 at 9:24 am
Did you ever figure out how to trap the first error? I need to do that, too. Thanks.
October 9, 2009 at 10:26 am
Consider using code that catches the error and raises the error to the calling program:
proc1:
begin try
exec proc2;
end try
begin catch
declare
@errMsg varchar(1000),
@errState int,
@errSeverity int;
set @errState = error_state();
set @errSeverity = error_severity();
set @errMsg = error_message() + char(10) + error_procedure();
raiserror( @errMsg, @errSeverity, @errState );
end catch;
proc2:
begin try
<do stuff>
end try
begin catch
declare
@errMsg varchar(1000),
@errState int,
@errSeverity int;
set @errState = error_state();
set @errSeverity = error_severity();
set @errMsg = error_message() + char(10) + error_procedure();
raiserror( @errMsg, @errSeverity, @errState );
end catch;
Viewing 3 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply
This website stores cookies on your computer.
These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media.
To find out more about the cookies we use, see our Privacy Policy