I have been using something more or less like this in postgres to emulate how, in SQL Server, I have used Try/Catch blocks with transactions that can be rolled back in the Catch if an error is found:
do $$
begin
[SQL here]
exception when others then
raise notice 'Error in insert statement ---> % %', SQLERRM, SQLSTATE LINE;
end;
$$ language 'plpgsql';
Is there a way to report the line where the error occurred, like "ERROR_LINE()?
Thanks in advance
Syntax Using /* and */ symbols In PostgreSQL, a comment that starts with /* symbol and ends with */ and can be anywhere in your SQL statement. This method of commenting can span several lines within your SQL.
PostgreSQL only reports the info , warning , and notice level messages back to the client.
First, when an error occurs between the begin and exception , PL/pgSQL stops the execution and passes the control to the exception list. Second, PL/pgSQL searches for the first condition that matches the occurring error. Third, if there is a match, the corresponding handle_exception statements will execute.
if it is an user defined exception, delete the corresponding declaration and specify unique error code via ERRCODE in a USING clause. in catch-block replace SQLCODE by SQLSTATE.
On some modern PostgreSQL, you can use GET STACKED DIAGNOSTICS
statement. There is not possibility to get linenumber, but you can get a call context, where lineno is included:
postgres=> DO $$
DECLARE
a int DEFAULT 0;
_c text;
BEGIN
BEGIN
PERFORM 10/a;
EXCEPTION WHEN OTHERS THEN
GET STACKED DIAGNOSTICS _c = PG_EXCEPTION_CONTEXT;
RAISE NOTICE 'context: >>%<<', _c;
END;
END;
$$;
NOTICE: 00000: context: >>SQL statement "SELECT 10/a"
PL/pgSQL function inline_code_block line 7 at PERFORM<<
LOCATION: exec_stmt_raise, pl_exec.c:3041
DO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With