विशिष्ट exceptions कैप्चर करना
आइए एक DO फंक्शन बनाएँ जो तब कैप्चर करे जब glucose null सेट किया जाए, और एक संदेश लॉग करे जो स्पष्ट रूप से बताए कि Glucose null नहीं हो सकता.
यह अभ्यास पाठ्यक्रम का हिस्सा है
PostgreSQL में Transactions और Error Handling
अभ्यास निर्देश
- DO फंक्शन के
BEGINब्लॉक के अंदर,patientsमें वह rowINSERTकरें (a1c=7.5,glucose=null, औरfasting=TRUE). - एक
not_null_violationexception जोड़ें जो error की स्थिति मेंerrorsकी detail कॉलम में"Glucose can not be null."insert करे.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
-- Make a DO function
DO $$
-- Open a transaction block
BEGIN
INSERT INTO patients (a1c, glucose, fasting)
VALUES (7.5, ___, TRUE);
-- Catch an Exception
EXCEPTION
-- Make it catch not_null_constraint exception types
WHEN ___ ___
-- Insert the proper msg and detail
INSERT INTO errors (___, detail)
VALUES ('failed to insert', '___');
END$$;
-- Select all the errors recorded
SELECT * FROM errors;