Specific exceptions पर लॉगिंग संदेश
कई विशिष्ट exceptions को पकड़ने का एक बड़ा लाभ यह है कि आप हर एक के लिए अलग तरह से हैंडल कर सकते हैं और ऐसे यूनिक error संदेश लॉग कर सकते हैं जो यह स्पष्ट करें कि exception क्यों हुआ। आइए इसे ऐसे परिदृश्य में लागू करें जहाँ दोनों error स्थितियाँ संभव हैं। अभ्यास के बाद हम चर्चा करेंगे कि इसमें जो specific संदेश कैप्चर हुआ, वह क्यों हुआ।
यह अभ्यास पाठ्यक्रम का हिस्सा है
PostgreSQL में Transactions और Error Handling
अभ्यास निर्देश
not_null_violationके लिए एक exception हैंडलर बनाएँ।- यदि
not_null_violationहोता है, तोerrorsटेबल मेंmsgके रूप में"failed to insert"औरdetailके रूप मेंGlucose can not be null.इन्सर्ट करें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
-- Make a DO function
DO $$
-- Open a transaction block
___
INSERT INTO patients (a1c, glucose, fasting) values (20, null, TRUE);
-- Catch an Exception
EXCEPTION
-- Make it catch check_violation exception types
WHEN check_violation THEN
-- Insert the proper msg and detail
INSERT INTO errors (msg, detail)
VALUES ('failed to insert', 'A1C is higher than clinically accepted norms.');
-- Make it catch not_null_violation exception types
___ ___ ___
-- Insert the proper msg and detail
INSERT INTO errors (msg, detail)
___ (___, ___);
END$$;
-- Select all the errors recorded
SELECT * FROM errors;