如何打印代码,PostgreSQL / plpgsql 异常的类型

Joh*_*zer 2 postgresql error-handling exception

给定这个 pl/pgSQL 函数

drop function if exists f( float );
create function f( x float )
  returns float
  language plpgsql
  as $$
    begin
      return 1 / x;
    exception
      when others then
        raise notice 'oops';
        return 0::float;
    end;
  $$;
Run Code Online (Sandbox Code Playgroud)

很明显,这select f( 0 );将导致代码 22012 异常,类型division_by_zeroexception知道了这一点,我可以将子句的选择器范围缩小到when division_by_zero then ...

但是,对于任意函数,如何获取错误类型呢?有什么类似的东西吗raise notice error.code

kli*_*lin 5

使用sqlstate,示例:

drop function if exists f( float );
create function f( x float )
  returns float
  language plpgsql
  as $$
    begin
      return 1 / x;
    exception
      when others then
        raise notice 'oops %', sqlstate;
        return 0::float;
    end;
$$;

select f(0);

NOTICE:  oops 22012
 f 
---
 0
(1 row) 
Run Code Online (Sandbox Code Playgroud)

阅读有关错误和消息以及捕获错误的更多信息。