Check Transaction Context

Check transaction context

The Request class is a viable solution to your problem. Check the next page for details.

Have you ever needed your transaction to be context-aware? Have you wanted to call different logic depending on when it is invoked? Ever encountered an issue with calling a future method from another future method?

apex
Request.getCurrent().getQuiddity()

The Request class is a viable solution to your problem. Check the next page for details.

getQuiddity method will return one of the possible transaction contexts:

ANONYMOUS, AURA, BATCH_ACS, BATCH_APEX, BATCH_CHUNK_PARALLEL, BATCH_CHUNK_SERIAL, BULK_API, COMMERCE_INTEGRATION, DISCOVERABLE_LOGIN, EXTERNAL_SERVICE_CALLBACK, FUNCTION_CALLBACK, FUTURE, INBOUND_EMAIL_SERVICE, INVOCABLE_ACTION, PLATFORM_EVENT_PUBLISH_CALLBACK, POST_INSTALL_SCRIPT, QUEUEABLE, QUICK_ACTION, REMOTE_ACTION, REST, RUNTEST_ASYNC, RUNTEST_DEPLOY, RUNTEST_SYNC, SCHEDULED, SOAP, SYNCHRONOUS, TRANSACTION_FINALIZER_QUEUEABLE, VF

Let's see an example: a class that executes its logic in either a future or synchronous context, depending on whether the current context is a future method. This approach helps prevent the dreaded 'System.AsyncException: Future method cannot be called from a future or batch method.’

apex
public class MyFutureCall {

    public static void callMe() {
        if(Request.getCurrent().getQuiddity() == System.Quiddity.FUTURE) {
            mySyncMethod();
        } else {
            myFutureMethod();
        }
    }

    @future
    private static void myFutureMethod() {
        System.debug('Executing future method logic');
    }

    private static void mySyncMethod() {
        System.debug('Execute synchronous logic');
    }

}

Text and code were extracted from the original slide. Plain-text version of the whole catalog