Skip to content

Log exceptions where you raise them

Jörg Neumann edited this page Jan 14, 2022 · 1 revision

Anti-Pattern

Delegating the decision of whether to log an exception to the caller will always degrade the quality of the log. Some callers might log the exception before propagating it, others might not. Their respective callers might do the same. If you delegate the decision, an exception may be logged multiple times or not at all!

METHOD bad_method.
  SELECT [...]

  IF sy-subrc NE 0.
    RAISE EXCEPTION TYPE /usi/cx_bal_not_found
      EXPORTING
        textid = /usi/cx_bal_not_found=>no_db_entries_found.
  ENDIF.
ENDMETHOD.

A better way

The problem can easily be avoided by offering every raised exception to the log writer. The easiest and most consistent way to do this is to call the log writer, where you are raising the exception.

METHOD better_method.
  SELECT [...]
 
  IF sy-subrc NE 0.
    TRY.
        RAISE EXCEPTION TYPE /usi/cx_bal_not_found
          EXPORTING
            textid = /usi/cx_bal_not_found=>no_db_entries_found.
      CLEANUP INTO DATA(exception).
        /usi/cl_bal_factory=>get_instance( )->get_existing_logger( )->add_exception( exception ).
    ENDTRY.
  ENDIF.
ENDMETHOD.

The easiest way to implement this is "abusing" the CLEANUP block.

If you are logging every exception like this, you will automatically get a complete log with all exceptions, as soon, as the log level is high enough.

Clone this wiki locally