Background
I'm new to PostgreSQL and I'm having some issues with this trigger function, which I've obviously simplified considerably below. I could ask to help fix the query, but I think I can handle that, and what I'm more concerned about is that I have a lot of functions like this and I need a way to be able to have visibility into why it's failing, and which ones are failing.
Question
How can I catch exceptions that happen within this function and write them to some kind of log table so I can review and fix each one? Ideally I'd like to write the sql statement that failed to the log table as well so I can see specifically what went wrong. I've seen a few examples of similar things, but they don't seem to fit my scenario.
CREATE OR REPLACE FUNCTION my_func() RETURNS TRIGGER AS $$
BEGIN
IF (TG_OP = 'INSERT') THEN
INSERT INTO my_table(...)
SELECT ...
FROM table_1 t1
JOIN table_2 t2 ON t1.id = t2.id
ON CONFLICT (id)
DO UPDATE
field1 = EXCLUDED.field1;
ELSIF(TG_OP = 'UPDATE') THEN
UPDATE my_table
SET ...
FROM table_1 t1
JOIN table_2 t2 ON t1.id = t2.id
WHERE id = NEW.id;
ELSIF (TG_OP = 'DELETE') THEN
DELETE FROM my_table WHERE id= OLD.id;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

BEGIN ... EXCEPTION ... ENDblock.