Catch all error psql function exception

Pavan Ebbadi picture Pavan Ebbadi · Feb 2, 2017 · Viewed 15k times · Source

I am writing an function with exception catching and ignoring. I want to catch all the exceptions and just ignore it. Is there anyway to catch all the exceptions and not individually?

CREATE OR REPLACE FUNCTION ADD_TABLE_TO_ARCHIVE (a TEXT, b TEXT)
RETURNS INTEGER AS $SUCCESS$
DECLARE SUCCESS INTEGER;
BEGIN
    SUCCESS = 0;
    BEGIN
        UPDATE ARCHIVE_STATUS
        SET *****
        WHERE ***;
        SUCCESS = 1;
    EXCEPTION
        WHEN UNIQUE_VIOLATION 
        SUCCESS = 0;
    END;

   RETURN SUCCESS;
END;
$SUCCESS$ LANGUAGE plpgsql;

In place of unique exception, it should be any exception...

Answer

Pavel Stehule picture Pavel Stehule · Feb 2, 2017

You can use EXCEPTION WHEN OTHERS clause:

BEGIN
  do something
EXCEPTION WHEN OTHERS THEN
  handle any exception
END;

Without some exception a using of this clause is not good idea. The debugging, issue diagnostics can be terrible when you use this pattern. It is strong feature (sometimes necessary), but dangerous!