Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL custom exception conditions

Is it possible to create custom conditions when I raise an exception? Consider the following example:

BEGIN       
    y := x / 0;
EXCEPTION
    WHEN division_by_zero THEN
        RAISE NOTICE 'caught division_by_zero';
        RETURN x;
END;

Here I use 'division_by_zero' condition to catch the exception. What I'd like to do is something like this:

BEGIN       
    [...]
    RAISE custom_condition;
EXCEPTION
    WHEN custom_condition THEN
       [...]
END;

so that I don't interfere with possible standard exceptions. I could just do y:= 1 / 0; and catch division_by_zero, but it does not look right.

like image 300
Snifff Avatar asked Oct 14 '11 12:10

Snifff


People also ask

What is raise notice in PostgreSQL?

RAISE is used to raise errors and report messages, PostgreSQL provides various parameters to report an error, warning, and information at a detailed level.

What are the different raise statements?

Possible levels with RAISE are DEBUG , LOG , NOTICE , WARNING , INFO and EXCEPTION . EXCEPTION raises an error (which normally aborts the current transaction).

What is the maximum database size in PostgreSQL?

PostgreSQL normally stores its table data in chunks of 8KB. The number of these blocks is limited to a 32-bit signed integer (just over two billion), giving a maximum table size of 16TB.


1 Answers

begin
    if $1='bar' then
        raise exception using
            errcode='NOBAR',
            message='Bar is prohibited',
            hint='We do not talk to this guy';
    end if;
exception
    when sqlstate 'NOBAR' then
        update nobar_raised set count=count+1;
end;

More info:

  • Errors and Messages

  • Trapping Errors

like image 114
Tometzky Avatar answered Sep 21 '22 23:09

Tometzky