Sub topic 14
Logging errors that survive a rollback
This chapter assumes you can write an EXCEPTION section, re-raise with RAISE, and use COMMIT and ROLLBACK. It also assumes you have seen SQLERRM and DBMS_UTILITY.FORMAT_ERROR_STACK. Here you combine them so that an error record stays in the database after the failing work is rolled back.
The problem: the log row rolls back with everything else
A typical handler logs the error and then rolls back the failed work:
- The block does some DML.
- An error occurs.
- The handler inserts a row into
error_log. - The handler or the caller issues
ROLLBACK.
The INSERT into error_log belongs to the same transaction as the DML that failed. The rollback removes it, and you are left with no record of the failure. If you COMMIT the log row instead, you also commit the half-finished business changes, which is worse.
You need the log row to live in a separate transaction. An autonomous transaction provides that.
Autonomous transactions
PRAGMA AUTONOMOUS_TRANSACTION is a compiler directive placed in the declaration section of a subprogram. When that subprogram runs, Oracle suspends the caller's transaction and starts a new, independent one. The new transaction has its own COMMIT and ROLLBACK. When the subprogram ends, the caller's transaction resumes unchanged.
CREATE TABLE error_log (
logged_at TIMESTAMP DEFAULT SYSTIMESTAMP,
message VARCHAR2(4000)
);
CREATE OR REPLACE PROCEDURE log_error (p_msg IN VARCHAR2) IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO error_log (message) VALUES (p_msg);
COMMIT;
END log_error;
/The COMMIT here commits only the error_log insert. It does not touch the caller's uncommitted changes.
Using the logger in a handler
This block updates a row and then fails. The handler logs the error, rolls back, and re-raises. It assumes the HR sample data, where employee 100 exists.
BEGIN
UPDATE employees SET salary = salary * 1.1 WHERE department_id = 50;
UPDATE employees SET salary = salary / 0 WHERE employee_id = 100;
EXCEPTION
WHEN OTHERS THEN
log_error(DBMS_UTILITY.FORMAT_ERROR_STACK ||
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
ROLLBACK;
RAISE;
END;
/
SELECT logged_at, message FROM error_log ORDER BY logged_at;The block ends with ORA-01476: divisor is equal to zero, because RAISE passes the error on. The department 50 raises are rolled back. The SELECT still returns a row containing the stack and the line number from the backtrace.
The handler builds the message before calling log_error. That ordering matters, as the next section explains.
Capture error details first
SQLCODE, SQLERRM, and the DBMS_UTILITY formatting functions describe the exception currently being handled. Any statement that raises and handles its own exception, including one inside a procedure you call, can change what they return. Evaluate them in the handler and pass the text as an argument. Do not make the logger read them itself. The logger could end up reporting its own problems instead of the original error.
A logger that accepts a text parameter, as log_error does, avoids this.
The rules of an autonomous transaction
Autonomous transactions have restrictions that cause most of the errors people hit with logging code.
- It must end its transaction. If the subprogram does DML and returns without a
COMMITorROLLBACK, Oracle raisesORA-06519: active autonomous transaction detected and rolled back. Every exit path must end the transaction, including the exception path. - It cannot see the caller's uncommitted changes. The autonomous transaction is a separate session-level transaction. It reads only committed data. A logger that tried to look up a row the caller just inserted would find nothing.
- It can deadlock with its caller. If the autonomous code tries to change a row that the caller has locked, it waits for the caller. The caller is waiting for the autonomous code to return. Oracle detects this and raises
ORA-00060. A logger that only inserts into its own table avoids the problem. - Its commit is permanent. Once
log_errorcommits, the row stays even if the caller's code later fails. That is the goal here, but it is also why you should not use autonomous transactions for ordinary business logic. - It uses extra resources. Each call opens a transaction. Logging inside a loop that fails for every row can be expensive.
Making the logger safe
The logger is the one place in the code that must not fail loudly. If log_error raises an exception, such as when the table is full or a tablespace is unavailable, that exception replaces the original error inside the handler. The caller then sees the logging failure and never learns what went wrong in the first place.
The logger should also keep long messages from causing a failure. The parameter accepts far more than the 4000 characters the column holds.
CREATE OR REPLACE PROCEDURE log_error (p_msg IN VARCHAR2) IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO error_log (message)
VALUES (SUBSTR(p_msg, 1, 4000));
COMMIT;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK; -- end the autonomous transaction; do not mask the caller's error
END log_error;
/Swallowing every error is normally a mistake, but the logger is a deliberate exception. The ROLLBACK is required so the autonomous transaction ends on the failure path, which avoids ORA-06519. If you need to know when logging itself fails, write to DBMS_OUTPUT or another channel from that handler, but do not re-raise.
SUBSTR counts characters. With multibyte character sets, a 4000-character string can exceed 4000 bytes. In that case use SUBSTRB or declare the column with character semantics, such as VARCHAR2(4000 CHAR), which is still subject to the 4000-byte limit in some configurations.
Where to call the logger
Call it from the handler closest to where you have useful context, and decide whether to re-raise.
CREATE OR REPLACE PROCEDURE process_department (p_dept IN NUMBER) IS
BEGIN
UPDATE employees
SET salary = salary * 1.05
WHERE department_id = p_dept;
EXCEPTION
WHEN OTHERS THEN
log_error('process_department(' || p_dept || '): ' ||
DBMS_UTILITY.FORMAT_ERROR_STACK ||
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
RAISE;
END process_department;
/Including the subprogram name and its arguments in the message makes the row useful later. The RAISE at the end is also needed. Logging does not handle the error. It only records it, so the caller still needs to see the failure and decide what to do.
If an error passes through several layers, each with this pattern, you will log the same error several times. Pick one layer, usually the outermost one that owns the transaction, and log there. Inner layers can simply let the exception propagate.
Summary of the pattern
| Step | Where | Why |
|---|---|---|
| Build the message from `SQLERRM`, `FORMAT_ERROR_STACK`, and `FORMAT_ERROR_BACKTRACE` | In the handler | The error is still current there |
| Call `log_error` | In the handler, before the rollback or `RAISE` | The log row is committed independently |
| `ROLLBACK` the business work | In the handler or the caller | Undoes the partial changes |
| `RAISE` | Last statement in the handler | The caller still sees the failure |
Exercise
A procedure inserts a row into error_log using PRAGMA AUTONOMOUS_TRANSACTION but omits the COMMIT. What error does Oracle raise when the procedure returns, and how do you fix it?
Show answer
Oracle raises ORA-06519: active autonomous transaction detected and rolled back. Add a COMMIT after the INSERT, and also a ROLLBACK in the exception handler so that every exit path ends the autonomous transaction.
Exercise
A handler calls log_error, then runs ROLLBACK, then RAISE. A colleague moves the ROLLBACK before the log_error call. Does the log row still survive? Does the order change what the log contains?
Show answer
The log row still survives, because logerror commits in its own transaction and the caller's ROLLBACK does not affect it. The order does not change what is logged as long as the message is built from SQLERRM and the DBMSUTILITY functions before they are overwritten. Moving the ROLLBACK first is safe, but you should still build the message before running other statements that could change the error information.