Özel istisna yakalama ve iletiler

PostgreSQL'de İşlemler (Transaction) ve Hata Yönetimi

Jason Myers

Principal Engineer

Belirli bir istisna türünü yakalamak

DO $$
BEGIN
    UPDATE inventory SET quantity = quantity - 1 WHERE name in ('flour', 'sugar');
EXCEPTION
    WHEN check_violation THEN
           INSERT INTO errors (msg) VALUES ('Quantity can not be less than 0.');
           RAISE INFO 'Quantity can not be less than 0.';
END; 
$$ language 'plpgsql';
PostgreSQL'de İşlemler (Transaction) ve Hata Yönetimi

İstisna işleyicimizin çıktısı

INFO:  Quantity can not be less than 0.
DO
postgres=# select * from errors;
 error_id | state |               msg                | detail | context
^---------+-------+----------------------------------+--------+---------
        1 |       | Quantity can not be less than 0. |        |
(1 row)
PostgreSQL'de İşlemler (Transaction) ve Hata Yönetimi

Yaygın istisna koşulları türleri

Koşul Adı Örnek
unique_violation Benzersiz bir sütuna aynı değerden iki tane eklemek
not_null_violation Null kabul etmeyen bir alana null eklemek
check_violation Lezzetlilikte 11’in üzerinde olma gibi bir check kısıtını ihlal etmek
division_by_zero 0’a bölmek

Daha fazlası için aşağıdaki bağlantıya bakınız

1 https://www.postgresql.org/docs/9.4/errcodes-appendix.html
PostgreSQL'de İşlemler (Transaction) ve Hata Yönetimi

Birden çok istisnayı yakalamak

DO $$
BEGIN
    UPDATE inventory SET quantity = quantity - 6, cost = null 
    WHERE name='oatmeal dark chocolate';

PostgreSQL'de İşlemler (Transaction) ve Hata Yönetimi

Birden çok istisna türünü ayrı ayrı yakalamak

-- check_violation istisnasını ekleyin
EXCEPTION
  WHEN check_violation THEN
     INSERT INTO errors (msg) VALUES ('Quantity can not be less than 0.');
     RAISE INFO 'Quantity can not be less than 0.';

-- not_null istisnasını ekleyin
  WHEN not_null_violation THEN
     INSERT INTO errors (msg) VALUES ('Cost can not be null.');
     RAISE INFO 'Cost can not be null.';
END; $$ language 'plpgsql';

PostgreSQL'de İşlemler (Transaction) ve Hata Yönetimi

Birden çok istisna yakalama çıktısı

INFO:  Cost can not be null.
DO
postgres=# select * from errors;
 error_id | state |               msg                | detail | context
^---------+-------+----------------------------------+--------+---------
        2 |       | Cost can not be null.            |        |
(1 row)
PostgreSQL'de İşlemler (Transaction) ve Hata Yönetimi

Uygulama zamanı!

PostgreSQL'de İşlemler (Transaction) ve Hata Yönetimi

Preparing Video For Download...