0

In Postgresql is there a way to get the error message/description from error code:

https://github.com/postgres/postgres/blob/master/src/backend/utils/errcodes.txt

I need it to be automated, a function will be fine, something like this:

CREATE OR REPLACE FUNCTION ErrorMessage(IN Code char(5))
returns varchar(100)
AS $BODY$
begin
  return ????;
end;
$BODY$ LANGUAGE PLPGSQL;

1 Answer 1

4

I think what you are looking for lies here : https://www.postgresql.org/docs/11/plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING

So if you want to have details about an error you may treat your transactions as follows:

DECLARE
  text_var1 text;
  text_var2 text;
  text_var3 text;
BEGIN
  -- some processing which might cause an exception
  ...
EXCEPTION WHEN OTHERS THEN
  GET STACKED DIAGNOSTICS text_var1 = MESSAGE_TEXT,
                          text_var2 = PG_EXCEPTION_DETAIL,
                          text_var3 = PG_EXCEPTION_HINT;
END;

But if you still want to have the corresponding error designation based on the error code (https://www.postgresql.org/docs/current/errcodes-appendix.html), then you can build a table with all the infos in it (PG_ERROR_CODES(id varchar(64), description varchar(255))) and interrogate it with your function.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, i wanted to do that but the problem with this solution is that when the list change or some new errors are added (maybe in new realeases) i have to add the new messages to my list too...
Why do you need such a feature? Maybe there is a workaround that is compliant with PGSQL philosophy.
I am converting a code from another database where I check always for the last error but there is no last error in PostgreSQL
if there is a way to get the last SQLSTATE that will be great for me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.