1

I'm using Postgres with Golang via pgx

I've a trigger function something like the following:

CREATE OR REPLACE FUNCTION foo() 
RETURNS TRIGGER AS
$$
BEGIN
    IF (bar = 'baz') THEN
        -- something
    ELSE
        RAISE EXCEPTION 'oops error';
    END IF;
    RETURN NEW;
END;
$$
LANGUAGE plpgsql;

How do I check for oops error in Go code?

The way I'm doing it now is:

errOops := errors.New("ERROR: oops error (SQLSTATE P0001)")
err := myDBFunc()
if errors.Is(err, errOops) {

}

But I wonder if there's a better way other than relying on the hardcoded message.

Abhijit
  • 468
  • 8
  • 22

2 Answers2

3

Should have read the Wiki: Error Handling in pgx

So I can do:

var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "P0001" {

}

or something similar.

Abhijit
  • 468
  • 8
  • 22
1

You can find that information in appendix A of the documentation: it will be a raise_exception, and the SQLSTATE is P0001.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
  • 1
    Hi. Thanks for replying. But I meant how to check it in Golang code. The code only returns an `error` type which, if I marshal to JSON and log, I get the code and message etc. But the actual variable, let's call it `err` only has an `Error` method (as expected). – Abhijit Oct 18 '22 at 11:20
  • 1
    Great, you found the missing information yourself. – Laurenz Albe Oct 18 '22 at 12:20