2

Given this pl/pgSQL function

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;
  $$;

it is clear that select f( 0 ); will result in an code 22012 exception, type division_by_zero. Knowing this I can narrow down the selector of the exception clause to when division_by_zero then ....

However, for arbitrary functions, how can I obtain the error type? Is there anything like, say, raise notice error.code?

1 Answer 1

5

Use sqlstate, example:

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) 

Read more about Errors and Messages and Trapping Errors.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.