|
| 1 | +# G-5080: Always use FORMAT_ERROR_BACKTRACE when using FORMAT_ERROR_STACK or SQLERRM. |
| 2 | + |
| 3 | +!!! tip "Minor" |
| 4 | + Maintainability, Testability |
| 5 | + |
| 6 | +## Reason |
| 7 | + |
| 8 | +In exception handler `sqlerrm` and `format_error_stack` won't tell you the exact line where the error occurred. `format_error_backtrace` displays the call stack at the point where an exception was raised, even if the subprogram is called from an exception handler in an outer scope. |
| 9 | + |
| 10 | +If you use `sqlerrm` or `format_error_stack` to log/display error, you should also include `format_error_backtrace` to identify the exact location where the exception was raised. |
| 11 | + |
| 12 | +## Example (bad) |
| 13 | + |
| 14 | +``` sql |
| 15 | +create or replace package body order_api as |
| 16 | + procedure discount_and_recalculate( |
| 17 | + in_customer_id customer.id%type |
| 18 | + , in_discount customer.discount_percentage%type |
| 19 | + ) |
| 20 | + begin |
| 21 | + customer_api.apply_discount(in_customer_id, in_discount); |
| 22 | + customer_api.in_customer_id(10293847); |
| 23 | + exception |
| 24 | + when zero_divide then |
| 25 | + null; -- ignore |
| 26 | + when others then |
| 27 | + logging_package.log_error('Error: ' || sqlerrm); |
| 28 | + raise; |
| 29 | + end discount_and_recalculate; |
| 30 | +end order_api; |
| 31 | +/ |
| 32 | +``` |
| 33 | + |
| 34 | +## Example (good) |
| 35 | + |
| 36 | +``` sql |
| 37 | +create or replace package body order_api as |
| 38 | + procedure discount_and_recalculate( |
| 39 | + in_customer_id customer.id%type |
| 40 | + , in_discount customer.discount_percentage%type |
| 41 | + ) |
| 42 | + begin |
| 43 | + customer_api.apply_discount(in_customer_id, in_discount); |
| 44 | + customer_api.in_customer_id(10293847); |
| 45 | + exception |
| 46 | + when zero_divide then |
| 47 | + null; -- ignore |
| 48 | + when others then |
| 49 | + logging_package.log_error( |
| 50 | + 'Error: ' || sqlerrm || ' - Backtrace: ' || dbms_utility.format_error_backtrace |
| 51 | + ); |
| 52 | + raise; |
| 53 | + end discount_and_recalculate; |
| 54 | +end order_api; |
| 55 | +/ |
| 56 | +``` |
0 commit comments