, , , catch?
, catch. :
create table mySimpleTable
(
Id int not null primary key
, StringVar varchar(8) null
, IntVar tinyint null
)
go
, .
, . (-), , . , , . catch Log4TSql, SourceForge.
, , - , catch, , . raiserror ( throw SQL2012) catch. , , , (.. ).
create procedure mySimpleTableInsert
(
@Id int
, @StringVar varchar(16) = null
, @IntVar int = null
)
as
begin
declare @_FunctionName nvarchar(255) = quotename(object_schema_name(@@procid))
+ '.' + quotename(object_name(@@procid));
declare @_Error int = 0;
declare @_ReturnValue int;
declare @_RowCount int = 0;
declare @_Step varchar(128);
declare @_Message nvarchar(1000);
declare @_ErrorContext nvarchar(512);
begin try
set @_Step = 'Validate Inputs'
if @Id is null raiserror('@Id is invalid: %i', 16, 1, @Id);
set @_Step = 'Add Row'
insert dbo.mySimpleTable (Id, StringVar, IntVar)
values (@Id, @StringVar, @IntVar)
end try
begin catch
set @_ErrorContext = 'Failed to add row to mySimpleTable at step: '
+ coalesce('[' + @_Step + ']', 'NULL')
exec log4.ExceptionHandler
@ErrorContext = @_ErrorContext
, @ErrorProcedure = @_FunctionName
, @ErrorNumber = @_Error out
, @ReturnMessage = @_Message out
;
end catch
if @_Error > 0 raiserror(@_Message, 16, 99);
set nocount off;
return (@_Error);
end
go
() .
exec tSQLt.NewTestClass 'mySimpleTableInsertTests' ;
go
- , catch, . exec tSQLt.ExpectException , , @Id NULL ( )
create procedure [mySimpleTableInsertTests].[test throws error from catch block]
as
begin
exec tSQLt.ExpectException @ExpectedErrorNumber = 50000;
exec dbo.mySimpleTableInsert @Id = null
end;
go
tsqlt.SpyProcedure "" ExceptionHandler, . , , tSQLt , , , spied , . . , ExceptionHandler . , ExceptionHander mySimpleTableInsert .
create procedure [mySimpleTableInsertTests].[test calls ExceptionHandler on error]
as
begin
exec tsqlt.SpyProcedure 'log4.ExceptionHandler', 'set @ErrorNumber = 0;';
select
cast('Failed to add row to mySimpleTable at step: [Validate inputs]' as varchar(max)) as [ErrorContext]
, '[dbo].[mySimpleTableInsert]' as [ErrorProcedure]
into
exec dbo.mySimpleTableInsert @Id = null
select
ErrorContext
, ErrorProcedure
into
from
log4.ExceptionHandler_SpyProcedureLog;
exec tSQLt.AssertEqualsTable '
end;
go
, ( ) , , , @IntVar :
create procedure [mySimpleTableInsertTests].[test calls ExceptionHandler on invalid IntVar input]
as
begin
exec tsqlt.SpyProcedure 'log4.ExceptionHandler', 'set @ErrorNumber = 0;';
select
cast('Failed to add row to mySimpleTable at step: [Add Row]' as varchar(max)) as [ErrorContext]
, '[dbo].[mySimpleTableInsert]' as [ErrorProcedure]
into
exec dbo.mySimpleTableInsert @Id = 1, @IntVar = 500
select
ErrorContext
, ErrorProcedure
into
from
log4.ExceptionHandler_SpyProcedureLog;
exec tSQLt.AssertEqualsTable '
end;
go
create procedure [mySimpleTableInsertTests].[test throws error on invalid IntVar input]
as
begin
exec tSQLt.ExpectException @ExpectedErrorNumber = 50000;
exec dbo.mySimpleTableInsert @Id = 1, @IntVar = 500
end;
go
, , , .