スタック診断を取得する
スタック診断を使うと、PostgreSQL の内部エラーメッセージや例外の詳細を取得できます。patients テーブルに戻り、検査上限を超える A1C を追加してみましょう。これにより CHECK 制約の例外が発生し、捕捉できます。例外ハンドラー内でスタック診断を使うと、エラー記録を充実させられます。
この演習はコースの一部です
PostgreSQL におけるトランザクションとエラー処理
演習の手順
DECLAREでexc_messageとexc_detailの2つの変数を text 型として宣言します。- 診断スタックを取得し、
exc_messageにMESSAGE_TEXTを、exc_detailにPG_EXCEPTION_DETAILを設定します。 - errors テーブルの
msgフィールドとdetailフィールドに、それぞれexc_messageとexc_detailを挿入します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
DO $$
-- Declare our text variables: exc_message and exc_detail
___
___ text;
exc_detail ___;
BEGIN
INSERT INTO patients (a1c, glucose, fasting)
values (20, 89, TRUE);
EXCEPTION
WHEN others THEN
-- Get the exception message and detail via stacked diagnostics
___ ___ ___
exc_message = ___,
exc_detail = ___;
-- Record the exception message and detail in the errors table
INSERT INTO errors (___, detail) VALUES (exc_message, ___);
END;
$$ language 'plpgsql';
-- Select all the errors recorded
SELECT * FROM errors;