특정 예외 처리와 메시지

PostgreSQL에서의 트랜잭션과 오류 처리

Jason Myers

Principal Engineer

특정 유형의 예외 포착하기

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에서의 트랜잭션과 오류 처리

예외 처리기 출력

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에서의 트랜잭션과 오류 처리

일반적인 예외 조건 유형

Condition Name Example
unique_violation 유니크 컬럼에 중복 값 삽입
not_null_violation NULL을 허용하지 않는 필드에 NULL 삽입
check_violation 맛 점수 11 초과 같은 CHECK 제약 위반
division_by_zero 0으로 나누기

더 많은 예시는 아래 인용 링크에서 확인하세요

1 https://www.postgresql.org/docs/9.4/errcodes-appendix.html
PostgreSQL에서의 트랜잭션과 오류 처리

여러 예외 포착하기

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

PostgreSQL에서의 트랜잭션과 오류 처리

여러 예외 유형을 개별 처리하기

-- Add check_violation exception
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.';

-- Add non-null exception
  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에서의 트랜잭션과 오류 처리

여러 예외 처리 결과

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에서의 트랜잭션과 오류 처리

이제 적용해 봅시다!

PostgreSQL에서의 트랜잭션과 오류 처리

Preparing Video For Download...