-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy path02-Handling Errors.sql
More file actions
37 lines (34 loc) · 909 Bytes
/
02-Handling Errors.sql
File metadata and controls
37 lines (34 loc) · 909 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
-- catch an error
BEGIN TRY
UPDATE SalesLT.Product
SET ProductNumber = ProductID / ISNULL(Weight, 0);
END TRY
BEGIN CATCH
PRINT 'The following error occurred:';
PRINT ERROR_MESSAGE();
END CATCH;
-- Catch and rethrow
BEGIN TRY
UPDATE SalesLT.Product
SET ProductNumber = ProductID / ISNULL(Weight, 0);
END TRY
BEGIN CATCH
PRINT 'The following error occurred:';
PRINT ERROR_MESSAGE();
THROW;
END CATCH;
-- Catch, log, and throw a custom error
BEGIN TRY
UPDATE SalesLT.Product
SET ProductNumber = ProductID / ISNULL(Weight, 0);
END TRY
BEGIN CATCH
DECLARE @ErrorLogID as int, @ErrorMsg AS varchar(250);
EXECUTE dbo.uspLogError @ErrorLogID OUTPUT;
SET @ErrorMsg = 'The update failed because of an error. View error #'
+ CAST(@ErrorLogID AS varchar)
+ ' in the error log for details.';
THROW 50001, @ErrorMsg, 0;
END CATCH;
-- View the error log
SELECT * FROM dbo.ErrorLog;