특정 예외에 대한 로그 메시지 남기기
여러 개의 특정 예외를 포착하는 가장 좋은 활용법 중 하나는, 예외가 발생한 정확한 원인을 이해할 수 있도록 고유한 오류 메시지를 구분해 처리하고 로깅하는 것입니다. 이번에는 두 가지 오류 조건이 모두 발생할 수 있는 상황에 이를 적용해 보겠습니다. 연습 문제 후에, 왜 해당 특정 메시지가 기록되었는지 함께 살펴보겠습니다.
이 연습은 강의의 일부입니다
PostgreSQL에서의 트랜잭션과 오류 처리
연습 안내
not_null_violation에 대한 예외 처리기를 작성하세요.not_null_violation이 발생하면errors테이블에msg는"failed to insert",detail은Glucose can not be null.로 INSERT 하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
-- Make a DO function
DO $$
-- Open a transaction block
___
INSERT INTO patients (a1c, glucose, fasting) values (20, null, TRUE);
-- Catch an Exception
EXCEPTION
-- Make it catch check_violation exception types
WHEN check_violation THEN
-- Insert the proper msg and detail
INSERT INTO errors (msg, detail)
VALUES ('failed to insert', 'A1C is higher than clinically accepted norms.');
-- Make it catch not_null_violation exception types
___ ___ ___
-- Insert the proper msg and detail
INSERT INTO errors (msg, detail)
___ (___, ___);
END$$;
-- Select all the errors recorded
SELECT * FROM errors;