用堆疊診斷強化例外處理

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';
PostgreSQL 的交易與錯誤處理

使用堆疊診斷

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$$;
PostgreSQL 的交易與錯誤處理

診斷輸出範例

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).
PostgreSQL 的交易與錯誤處理

可以取得哪些資訊?

Name Description
RETURNED_SQLSTATE 例外的 SQLSTATE 錯誤代碼
COLUMN_NAME 與例外相關的欄位名稱
CONSTRAINT_NAME 與例外相關的約束名稱
MESSAGE_TEXT 例外的主訊息文字
PG_EXCEPTION_DETAIL 例外的詳細訊息(若有)
1 https://www.postgresql.org/docs/12/plpgsql-control-structures.html
PostgreSQL 的交易與錯誤處理

更多診斷欄位

Name Description
PG_DATATYPE_NAME 與例外相關的資料型別名稱
TABLE_NAME 與例外相關的資料表名稱
SCHEMA_NAME 與例外相關的結構描述名稱
PG_EXCEPTION_HINT 例外的提示訊息文字(若有)
PG_EXCEPTION_CONTEXT 例外發生當下呼叫堆疊的文字行
PostgreSQL 的交易與錯誤處理

一起來練習吧!

PostgreSQL 的交易與錯誤處理

Preparing Video For Download...