การเพิ่มประสิทธิภาพการจัดการข้อยกเว้นด้วย stacked diagnostics

Transactions and Error Handling in PostgreSQL

Jason Myers

Principal Engineer

การดึงข้อมูลข้อผิดพลาดเพิ่มเติม

DO $$
BEGIN
   UPDATE inventory SET cost = 35.0 WHERE name = 'Macaron';
   UPDATE inventory SET cost = 3.50 WHERE name = 'Panellets';
EXCEPTION
   WHEN others THEN
       INSERT INTO errors (msg) VALUES ('Max cost is 10!');
       RAISE INFO 'Max cost is 10!';
END; 
$$ language 'plpgsql';
Transactions and Error Handling in PostgreSQL

การใช้งาน stacked diagnostics

DO $$
DECLARE
   exc_message text;
   exc_detail text;

BEGIN UPDATE inventory SET cost = 35.0 WHERE name = 'Macaron'; UPDATE inventory SET cost = 3.50 WHERE name = 'Panellets';
EXCEPTION WHEN others THEN GET STACKED DIAGNOSTICS exc_message = MESSAGE_TEXT, exc_detail = PG_EXCEPTION_DETAIL; INSERT INTO errors (msg, detail) VALUES (exc_message, exc_detail); RAISE INFO 'Exception Messaage: % | Exception Details: %', exc_message, exc_detail; END$$;
Transactions and Error Handling in PostgreSQL

ตัวอย่างผลลัพธ์ของ diagnostics

INFO:  Exception Messaage: new row for relation "inventory" violates check constraint 
"cost_check" | Exception Details: Failing row contains (7, 35, Macaron).
DO

postgres=# \x on
Expanded display is on.
postgres=# select msg, detail from errors;
-[ RECORD 1 ]-------------------------------------------------------------------
msg    | new row for relation "inventory" violates check constraint "cost_check"
detail | Failing row contains (7, 35, Macaron).
Transactions and Error Handling in PostgreSQL

ข้อมูลที่ดึงได้มีอะไรบ้าง?

Name Description
RETURNED_SQLSTATE รหัสข้อผิดพลาด SQLSTATE ของข้อยกเว้น
COLUMN_NAME ชื่อคอลัมน์ที่เกี่ยวข้องกับข้อยกเว้น
CONSTRAINT_NAME ชื่อ constraint ที่เกี่ยวข้องกับข้อยกเว้น
MESSAGE_TEXT ข้อความหลักของข้อยกเว้น
PG_EXCEPTION_DETAIL ข้อความรายละเอียดของข้อยกเว้น (ถ้ามี)
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html
Transactions and Error Handling in PostgreSQL

ข้อมูล diagnostics เพิ่มเติม

Name Description
PG_DATATYPE_NAME ชื่อชนิดข้อมูลที่เกี่ยวข้องกับข้อยกเว้น
TABLE_NAME ชื่อตารางที่เกี่ยวข้องกับข้อยกเว้น
SCHEMA_NAME ชื่อ schema ที่เกี่ยวข้องกับข้อยกเว้น
PG_EXCEPTION_HINT ข้อความ hint ของข้อยกเว้น (ถ้ามี)
PG_EXCEPTION_CONTEXT บรรทัดของ call stack ในขณะที่เกิดข้อยกเว้น
Transactions and Error Handling in PostgreSQL

มาฝึกกันเถอะ!

Transactions and Error Handling in PostgreSQL

Preparing Video For Download...