Context stack कैप्चर करना
Stack context लेना, जो अन्य भाषाओं के stack trace जैसा होता है, जटिल और nested फंक्शन को debug करने का एक शक्तिशाली तरीका है.
नीचे दिए गए कोड में, हम stack context को कैप्चर करना चाहते हैं और उसे दोनों nested ब्लॉक्स के exception handlers में रिकॉर्ड करना चाहते हैं. फिर, हम errors टेबल में उसके आउटपुट की समीक्षा करेंगे ताकि यह debug कर सकें कि इस फंक्शन में exception किस वजह से आ रहा है.
यह अभ्यास पाठ्यक्रम का हिस्सा है
PostgreSQL में Transactions और Error Handling
अभ्यास निर्देश
- stack context रखने के लिए
exc_contextनाम का एक text वैरिएबल घोषित करें. - पहले हैंडलर में
PG_EXCEPTION_CONTEXTको हमारेexc_contextवैरिएबल में सहेजें. - दूसरे हैंडलर में
PG_EXCEPTION_DETAILको हमारेexc_detailवैरिएबल में सहेजें. - दोनों ब्लॉक्स में error message और stack context, दोनों को रिकॉर्ड करें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
DO $$
DECLARE
exc_message text;
exc_details text;
-- Declare a variable, exc_context to hold the exception context
___ ___;
BEGIN
BEGIN
INSERT INTO patients (a1c, glucose, fasting) values (5.6, 93, TRUE),
(6.3, 111, TRUE),(4.7, 65, TRUE);
EXCEPTION
WHEN others THEN
-- Store the exception context in exc_context
GET STACKED DIAGNOSTICS exc_message = MESSAGE_TEXT,
___ = ___;
-- Record both the msg and the context
INSERT INTO errors (msg, context)
VALUES (___, ___);
END;
BEGIN
UPDATE patients set fasting = 'true' where id=1;
EXCEPTION
WHEN others THEN
-- Store the exception detail in exc_details
GET STACKED DIAGNOSTICS exc_message = MESSAGE_TEXT,
___ = ___;
INSERT INTO errors (___, ___)
VALUES (exc_message, exc_context);
END;
END$$;
SELECT * FROM errors;