Handling and logging ORA-06512 error code - oracle

I have just created an error_log table to log any errors that a procedure/package may run into. the error log table is as follows
CREATE TABLE APMS.ERROR_LOG
(
ORA_ERR_TMSP TIMESTAMP(6) NOT NULL,
ORA_ERR_NUMBER NUMBER(5) NOT NULL,
ORA_ERR_MSG VARCHAR2(200 CHAR) NOT NULL,
ORA_ERR_TXT VARCHAR2(500 CHAR) NOT NULL,
ORA_ERROR_OPTYP CHAR(1 CHAR) NOT NULL,
PROGRAM_NAME VARCHAR2(50 CHAR) NOT NULL,
ORA_IN_OUT VARCHAR2(500 CHAR) NOT NULL
)
I created a mock table an purposely induced the ORA-06512 error by inserting a character string in a timestamp field using a procedure. here is the procedure which inserts dummy data into my mock table with the purpose of inducing an error and logging it into my error_log table.
create or replace procedure test_procedure as
begin
insert into mockdata values ('data1','mockname','mockcity');
commit;
exception
when others then
insert into error_log
values
(ora_err_tmsp,ora_err_number,ora_err_msg,ora_err_txt,ora_err_optyp,program_name,ora_in_out);
values
(current_timestamp,sqlcode,'sqlerrm', 'detailed information','i','test_procedure','i');
commit;
end;
/
when I attempt to run/compile it I get the following error.
[Error] PLS-00103 (9: 1): PLS-00103: Encountered the symbol "VALUES" when expecting one of the following:
( begin case declare end exit for goto if loop mod null
pragma raise return select update when while with
<an
I am a complete beginner at pl/sql so any help is appreciated.

Before getting into your code: if you are planning to write that kind of logging in every procedure you write, maybe you should simply avoid doing it and keep at reach of your hand this trigger and enable it just when you need it: this trigger might be handy in a testing environment or if you are in deep trouble and you need to collect all possible error that happen in a given time:
CREATE OR REPLACE TRIGGER log_all_errors AFTER SERVERERROR ON DATABASE
declare
procedure log_error is
pragma autonomous_transaction;
begin
INSERT INTO error_log
VALUES (SYSDATE, SYS.LOGIN_USER, SYS.INSTANCE_NUM, SYS.DATABASE_NAME, DBMS_UTILITY.FORMAT_ERROR_STACK);
commit;
end;
BEGIN
log_error;
END log_all_errors ;
this trigger will log ALL errors that will happen in your system. it is not a good idea to keep it enabled permanently: you can use it for doing some troubleshooting in emergency and you might want adjust its code to log only some kind of errors, but it is a starting point.
if you do some research you will discover that you can even log the SQL text of the statement that caused the error.
keep in mind that there are some errors that are not catched by this trigger (i am referring to NO_DATA_FOUND and TOO_MANY_ROWS errors): there is simply too much code that normally uses these exceptions during its normal lifetime, so the guys at oracle decided not to trap these errors.
Now let's get back to your code: your approach, as other have pointed out, is not neutral to the normal execution of the program:
you are logging the error, right, but you are hiding the error to the program calling your procedure. It is not a good idea: the calling program surely would like to know that something wrong has happened and it would like to issue a "rollback" in order to cancel all previous work, instead of continuing like nothing wrong did happen.
Not only you are hiding the error, but you are also issuing a commit whenever an error happens: this is most likely the opposite of what your calling program would do in case of an error: surely the caller would issue a rollback. Instead you are making permanent all the partial work done until the error happened.
as a side note: the above problem of the unwanted commit even when no errors happen within your procedure: you are committing also when no errors are raised. this means that if the calling program enconuters some problems after having called your procedure, it won't be able to rollback anything it did before calling your code.
It generally is a bad practice to commit or rollback inside a procedure, unless you are more than sure that such procedure will never be called as part of a bigger transaction (for example: it is ok to commit if your procedure is the main body of a database job)
So: how can you write an error log without interfering with the calling program? you do it by writing the log in a dedicted autonomous transaction" procedure: whatever you do in procedure marked as "authonomous transaction" runs in its own separate transaction: you commit or rollback only what happens inside it.
(As you can see, I used an autonomous transaction also in the above trigger)
your code would be more "kind", to the calling program, if written this way:
CREATE OR REPLACE PROCEDURE test_procedure AS
procedure write_error_log (errcode number, errstr varchar2) is
pragma autonomous_transaction;
-- whatever we do in this procedure stays in its own new private transaction
begin
INSERT INTO error_log
(ora_err_tmsp,
ora_err_number,
ora_err_msg,
ora_err_txt,
ora_err_optyp,
program_name,
ora_in_out)
values (CURRENT_TIMESTAMP,
errcode,
errstr,
'detailed information',
'i',
'test_procedure',
'i');
COMMIT; -- this commit does not interfere with the caller's transaction.
end write_error_log;
BEGIN
INSERT INTO mockdata
VALUES ('data1', 'mockname', 'mockcity');
--here you were committing: you'd better not do it:
-- you are making impossible for the calling program to roll back
-- COMMIT;
exception when others then
write_error_log(sqlcode,sqlerrm);
raise; -- you should NOT hide the exception to the caller program, so you'd better re-raise it!
END test_procedure;

Try this:
CREATE OR REPLACE PROCEDURE test_procedure
AS
BEGIN
INSERT INTO mockdata
VALUES ('data1', 'mockname', 'mockcity');
COMMIT;
EXCEPTION
WHEN OTHERS
THEN
INSERT INTO error_log
(ora_err_tmsp,
ora_err_number,
ora_err_msg,
ora_err_txt,
ora_err_optyp,
program_name,
ora_in_out)
values (CURRENT_TIMESTAMP,
SQLCODE,
sqlerrm,
'detailed information',
'i',
'test_procedure',
'i');
COMMIT;
END;
/

Related

Can a trigger in Oracle saves data to log table and raises an exception as well?

guys:
I wonder if there is a way to write a trigger in Oracle to do both things: saving data to a log table and raising a user defined exception as well?
I am trying to figure out a strange error on my team's database, which causes data inconsistency per business logic. Multiple team's application can access this database. So I wrote a trigger to monitor certain column in a table which causes the problem. I want to save data such as user ID, saving time etc. to a log table if value is incorrect, but I also want to raise exception to attract attention. However, whenever my trigger raises the user defined exception, saving data to log table is not finished. Can anyone give a suggestion about it? Thank you in advance.
You can write a logging function that uses an autonomous transaction
create or replace procedure log_autonomous( p_log_message in varchar2,
p_other_parameters... )
as
pragma autonomous_transaction;
begin
insert into log_table ...
commit;
end;
and then call that logging function from your trigger
create or replace trigger my_trigger
before insert or update on some_table
for each row
declare
begin
if( some_bad_thing )
then
log_autonomous( 'Some message', ... );
raise_application_error( -20001, 'Some error' );
end if;
end;
The log_table message will be preserved because it was inserted in a separate (autonomous) transaction. The triggering transaction will be rolled back because the trigger raises an exception.

PL/SQL Continue after exception raised

I've got simple trigger with exception handling. My problem is how continue with application when user get error message.
CREATE OR REPLACE TRIGGER "AR_CHECK"
BEFORE INSERT ON TABLE
REFERENCING OLD AS OLD NEW AS NEW
FOR EACH ROW
DECLARE
v_check number;
cursor c_ar_check is
select ar_no
from name_view
where name_id = :new.bill_to_name_id
and name_type in ('TRAVEL_AGENT','COMPANY');
begin
open c_ar_check;
fetch c_ar_check into v_check;
close c_ar_check;
if v_check is null then
raise_application_error(-20101, 'ERROR - NUMBER MISSING');
end if;
end;
With code above I've got error message but user cannot continue with next step.
Is it possible to get user warning about NULL value but with possibility to go on?
With raise_application_error, no. It will terminate execution.
But, if you substitute it with something else - a trivial dbms_output.put_line would do in testing phase, while some logging process - such as calling a(n autonomous transaction) procedure - might be a better option in production.
If you choose dbms_output.put_line, note that your won't see any message until the procedure is finished.

Using a pl/sql procedure to log errors and handle exceptions

so far stack overflow and the oracle forums and docs have been my best friend in learning PLSQL. I'm running into an issue here. Any advice is appreciated. I'm writing a procedure that would be used to log any errors a package may encounter and log them into the error log table I created. here is my code thus far.
CREATE OR REPLACE PROCEDURE APMS.test_procedure AS
procedure write_error_log (errcode number, errstr varchar2, errline varchar2) is
pragma autonomous_transaction;
-- this procedure stays in its own new private transaction
begin
INSERT INTO error_log
(ora_err_tmsp,
ora_err_number,
ora_err_msg,
ora_err_line_no)
values (CURRENT_TIMESTAMP,
errcode,
errstr,
errline);
COMMIT; -- this commit does not interfere with the caller's transaction.
end write_error_log;
BEGIN
INSERT INTO mockdata
VALUES ('data1', 'mockname', 'mockcity');
exception when others then
write_error_log(sqlcode,sqlerrm,dbms_utility.format_error_backtrace);
raise;
END test_procedure;
/
In the procedure I currently am using a mockdata table to induce an invalid number error and log that to the error_log table. At this point the error log table proves to be functional and inserts the data needed. The next step for me is to use this procedure to be used in the exception handlers in other programs so that the error is caught and logged to the table. Currently, my procedure is only unique to the mock_data table. My mentor/superior is telling me I need to pass this program some parameters to use it in other packages and exception handlers. I'm just having a bit of trouble. Any help would be appreciated thank you!
Steven Feuerstein has written several articles in Oracle Magazine on how to handle errors in PLSQL. He offers a small framework (errpkg) for doing this. The DRY principle (Don't Repeat Yourself) is his mantra!
https://resources.oreilly.com/examples/0636920024859/blob/master/errpkg.pkg
First, you should not make your caller pass in errline. That's very tedious! And what happens when the developer needs to insert a line or two of code? Do they need to update every call to write_error_log after that point to update the line numbers? Your write_error_log should use dbms_utility.format_call_stack (or the 12c more convenient variant of that.. don't have its name handy) to figure out what line of code issued the call to write_error_log.
Then, you should have a 2nd procedure called, say, write_exception. All that needs to do is something like this:
write_error_log (SQLCODE, SUBSTR (DBMS_UTILITY.format_error_stack || DBMS_UTILITY.format_error_backtrace, 1, 4000));

Oracle - Update statement in Stored Procedure does not work once in a while

We have a stored procedure that inserts data into a table from some temporary tables in oracle database. There is an update statement after the insert that updates a flag in the same table based on certain checks. At the end of the stored procedure commit happens.
The problem is that the update works on 95% cases but in some cases it fails to update. When we try to run it again without changing anything, it works. Even trying to execute the same stored procedure on the same data at some other time, works perfectly. I haven't found any issues in the logic in the stored procedure. I feel there is some database level issue which we are not able to find (maybe related to concurrency). Any ideas on this would be very helpful.
Without seeing the source code we will just be guessing. The most obvious suggestion that I can think of is that it hits an exception somewhere along the way in some cases and never gets as far as the commit. Another possibility is that there is a lock on the table during execution when it fails.
Probably the best thing to investigate further would be to add an exception handler that writes the exceptions to some table or file and see what error is raised e.g.
-- create a logging table
create table tmp_error_log (timestamp timestamp(0), Error_test varchar2(1000));
-- add a variable to your procedure declaration
v_sql varchar2(1000);
-- add an exception handler just before the final end; statement on your procedure
exception
when others then
begin
v_sql := 'insert into tmp_error_log values(''' ||
to_char(sysdate, 'DD-MON-YYYY HH24:MI:SS') || ''', ''' || SQLERRM || ''')';
dbms_output.put_line(v_sql);
execute immediate v_sql;
commit;
end;
-- see what you get in the table
select * from tmp_error_log;

Oracle unique constraint on PK violated

I have a stored proc that I call from an external program to upsert data. The way the proc is setup is that it inserts into the table and on exception 'dup_val_on_index' it does an update instead.
How could I get this error if I'm catching the 'dup_val_on_index' exception and doing an update inside of it? I assume a PK would catch this specific exception since it creates a duplicate?
Yes, the dup_val_on_index named error would be raised for a primary key constraint error.
Perhaps your update is the code that is causing the error to be raised.
Why don't you just use MERGE in the first place?
In case you really don't want to use merge, just build an inner pl/sql-block and catch the exception there:
create or replace procedure proc(param1 varchar2)
as
some_var varchar2(50);
begin
-- do some things
begin
insert on your table;
exception when dup_val_on_index then
update on your table;
end;
--proceed with some more things
end proc;

Resources