Testing AuraHandledExceptions?

It seems like when I call getMessage on a thrown AuraHandledException, I see “Script-thrown Exception” instead of the message that I have set. Any idea why this may be happening?

Controller:

    @AuraEnabled
    public static Conversation__c makeConversation(String tonum, String objid)
    {
        if (tonum.length() != 10)
            throw new AuraHandledException('ToNumber length invalid.');
    }

TestController:

@isTest
    static void testMakeConversationInvalidTo()
    {
        Boolean testPass = false;
        String fromNumber = '1234567890';
        String toNumber = '1';

        List<ConversationController.ConversationWrapper> test =    ConversationController.getConversations();
        System.assertEquals(0, test.size());
        try {
            ConversationController.makeConversation(toNumber, '0');
        } catch (AuraHandledException e) {
            System.debug(e.getMessage());
            System.debug(e.getTypeName());
            System.assert(e.getMessage().contains('ToNumber length invalid'));
            testPass = true;
        }
    }

Return:

16:26:28:477 USER_DEBUG [320]|DEBUG|Script-thrown exception
16:26:28:477 USER_DEBUG [321]|DEBUG|System.AuraHandledException

Answer

The problem is that the constructor for the AuraHandledException only sets the string argument to be the message sent to the client-end, while calling getMessage() on the exception through apex returns a different string that the constructor defaults to the value “Script-thrown Exception”. Obviously, this leaves something to be desired for testing purposes, and I would suggest also adding the message to the exception with setMessage() so that it can be accessed through apex:

@AuraEnabled
public static void makeConversation(String tonum, String objid)
{
    if (tonum.length() != 10){
        AuraHandledException e = new AuraHandledException('ToNumber length invalid');
        e.setMessage('ToNumber length invalid');
        system.debug(e);
        throw e;
    }
}

Attribution
Source : Link , Question Author : Jason Lee , Answer Author : martin

Leave a Comment