In a PL/pgSQL function, I want to trap an error. For example, when I convert text to a number, I get an error (I run it in psql, but get the same error in the Postico GUI client):
select 'a'::numeric;
ERROR: invalid input syntax for type numeric: "a"
LINE 1: select 'a'::numeric;
^
To trap this error, I made an EXCEPTION-clause like this:
CREATE OR REPLACE FUNCTION public.to_number(input text) RETURNS numeric
AS $$
BEGIN
RETURN input::numeric;
EXCEPTION
WHEN OTHERS THEN
RETURN NULL;
END
$$
LANGUAGE plpgsql
IMMUTABLE
RETURNS NULL ON NULL INPUT
;
However, I don't like the condition WHEN OTHERS.
How do I map the error message ERROR: invalid input syntax for type numeric: "a" to one mentioned in the Appendix A. PostgreSQL Error Codes?
I want to catch the conversion error when converting to numeric and no other conditions (as the above function is a simplified one).
I have the feeling I'm missing something, but what?