pgsql存储过程--异常的捕获

在日常需求开发中,有时候会用到存储过程来预处理小量的数据集, 在此 需要记录存储过程的调度时长,是否正常执行 预警等

  • 案例
CREATE OR REPLACE FUNCTION "public"."project_statistics_copy1"()
  RETURNS "pg_catalog"."void" AS $BODY$
	-- Routine body goes here...
	-- 声明游标
DECLARE 
start_time varchar :=now();
err_message varchar;
exception_context varchar;

begin
//异常
select 1/0;
//异常的捕获
exception when others
    then 
		get stacked diagnostics exception_context=PG_EXCEPTION_CONTEXT ; --获取错误的行号
		
 			err_message := '错误行号:' || exception_context || ';  异常:' || sqlerrm; --获取异常信息
 			//异常记录
			PERFORM getexception('1111',0,start_time,err_message) ;

		
	RETURN ;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
CREATE OR REPLACE FUNCTION "public"."getexception"("fun_name" varchar, "status" int4, "start_time" varchar, "exceptions" varchar)
  RETURNS "pg_catalog"."void" AS $BODY$

BEGIN

insert into exception_detail(func_name,status,start_time,end_time,exceptions) 
--存储过程中对系统时间函数的调用,在事务内是不变的如 now(),可用 clock_timestamp() 来获取执行后的时间
values(fun_name,status,cast(start_time as timestamp),clock_timestamp(),exceptions);

	RETURN ;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  • 结果

在这里插入图片描述

你可能感兴趣的:(Pgsql,pgsql,存储过程,异常捕获,sqlerrm)