Nâng cao xử lý ngoại lệ với stacked diagnostics

Giao dịch và Xử lý Lỗi trong PostgreSQL

Jason Myers

Principal Engineer

Ghi nhiều thông tin lỗi hơn

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';
Giao dịch và Xử lý Lỗi trong PostgreSQL

Dùng 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$$;
Giao dịch và Xử lý Lỗi trong PostgreSQL

Ví dụ đầu ra chẩn đoán

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).
Giao dịch và Xử lý Lỗi trong PostgreSQL

Bạn có thể lấy những gì?

Name Description
RETURNED_SQLSTATE mã lỗi SQLSTATE của ngoại lệ
COLUMN_NAME tên cột liên quan đến ngoại lệ
CONSTRAINT_NAME tên ràng buộc liên quan đến ngoại lệ
MESSAGE_TEXT nội dung thông báo chính của ngoại lệ
PG_EXCEPTION_DETAIL nội dung thông báo chi tiết của ngoại lệ (nếu có)
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html
Giao dịch và Xử lý Lỗi trong PostgreSQL

Nhiều điểm dữ liệu chẩn đoán hơn

Name Description
PG_DATATYPE_NAME tên kiểu dữ liệu liên quan đến ngoại lệ
TABLE_NAME tên bảng liên quan đến ngoại lệ
SCHEMA_NAME tên schema liên quan đến ngoại lệ
PG_EXCEPTION_HINT văn bản gợi ý của ngoại lệ (nếu có)
PG_EXCEPTION_CONTEXT dòng ngữ cảnh của stack tại thời điểm xảy ra ngoại lệ
Giao dịch và Xử lý Lỗi trong PostgreSQL

Ayo berlatih!

Giao dịch và Xử lý Lỗi trong PostgreSQL

Preparing Video For Download...