For the last hours I got stuck on the problem, that I want a custom error (“Wrong airline_id. Please check your input again”) over the normal error code (insert or update on table “flightplan” violates foreign key constraint “fk_flightplan_airline”).
But no matter what I try, I always get the standard error. Please Help.
x
CREATE OR REPLACE FUNCTION add_flight(
PLAN_ID INT,
AIRLINE_ID INT,
STATUS_ID INT)
RETURNS void AS $BODY$
BEGIN
INSERT INTO flight.flightgplan VALUES(
PLAN_ID,
AIRLINE_ID,
STATUS_ID);
IF airline_id > 8 THEN RAISE EXCEPTION USING errcode = 99881;
ELSE IF status_id > 10 THEN RAISE EXCEPTION USING errcode = 99882;
END IF;
EXCEPTION
WHEN SQLSTATE '99881' THEN raise EXCEPTION 'Wrong airline_id. Please check your input again';
WHEN SQLSTATE '99882' THEN raise EXCEPTION 'Wrong status_id. Please check your input again';
END;
$BODY$ LANGUAGE plpgsql;
Advertisement
Answer
The custom exceptions should be thrown before performing the insert so that the insert will not be executed:
IF airline_id > 8 THEN RAISE EXCEPTION USING errcode = 99881;
ELSE IF status_id > 10 THEN RAISE EXCEPTION USING errcode = 99882;
END IF;
INSERT INTO flight.flightgplan VALUES(
PLAN_ID,
AIRLINE_ID,
STATUS_ID);