+ Start a Discussion
Andrew EAndrew E 
Hi all,

I have some apex code that looks like the code below. In my test class, I have a testMethod for successful execution, but I'm having trouble creating a testMethod for the exception. I've been able to trigger the exception, but the test is marked as Fail and I recieve "System.AuraHandledException: Script-thrown exception". As a result, I'm not getting code coverage for this exception.

How can I successfully test an AuraHandledException from a testMethod without breaking the test and having it result in a Fail?
try{
   update account;
}
catch(Exception e){
   throw new AuraHandledException('error updating account');
}

 
Best Answer chosen by Andrew E
Nayana KNayana K
In your test method also you have to add try catch block. Suppose if you set account.name blank they you know it will throw exception :

account.name  = '';

try
{
 //call the above method which updates the account
}
catch(Exception e) 
{

}
 
Best Answer chosen by Justin Thompson 9
Maharajan CMaharajan C
Hey Justin, You can't grey out the field only you can throw the validation msg using standard functionalities.
 
AND(
    NOT(ISPICKVAL(At_Risk_Reason__c,"Other")),
	NOT(ISBLANK(Other_Reason_Explanation__c))
)

Thanks,
Maharajan.C
Meenal Sankhla 12Meenal Sankhla 12 
calci.js file is:

import { LightningElement  ,track} from 'lwc';
export default class Calculator extends LightningElement {}
-----------------------------------------------------------------------------------------
calci.html file is 
<template>
<ligtning-card title="Calci" icon-name="standard:formula">
<ligtning-layout multiple-rows>
<lightning-layout-item size="12"  padding="around-medium">
<lightning-input type="number" name="FirstNumber"></lightning-input>
</lightning-layout-item>
<lightning-layout-item size="12"  padding="around-medium">
    <lightning-input type="number" name="SecondNumber"> </lightning-input>
        </lightning-layout-item>
        <lightning-layout-item size="12" padding="around-medium"> 
<lightning-button-group>
<lightning-button label="Add" icon-name="utility:add" icon:position="right"></lightning-button> 
<lightning-button label="Subtract" icon-name="utlity:dash"  icon:position="right"></lightning-button>
<lightning-button label="Multiply" icon-name="utlity:close" icon:position="right"></lightning-button>
<lightning-button label="Divide" icon-name="utlity:magicwand" icon:position="right"></lightning-button>
</lightning-button-group>
</lightning-layout-item>
<lightning-layout-item size="12"  padding="around-medium">
    <lightning-formated-text value={}></lightning-formated-text>
</lightning-layout-item>
</ligtning-layout>
</ligtning-card>
</template>
--------------------------------------------------------------------------
calci.js-meta.xml file is 
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="calci">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <description> Simple calculator app build with LWC</description>
    <targets>
    <target> lightning__AppPage  </target>
    <target> lightning__HomePage</target>
    <target> lightning_RecordPage</target>
    </targets>
</LightningComponentBundle>
Best Answer chosen by Meenal Sankhla 12
Sachin HoodaSachin Hooda
Hi Meenal,
It's because the last two closing tags are misspelled in your HTML file.
Please update your HTML file,
<template>
<lightning-card title="Calci" icon-name="standard:formula">
<lightning-layout multiple-rows>
<lightning-layout-item size="12"  padding="around-medium">
<lightning-input type="number" name="FirstNumber"></lightning-input>
</lightning-layout-item>
<lightning-layout-item size="12"  padding="around-medium">
    <lightning-input type="number" name="SecondNumber"> </lightning-input>
        </lightning-layout-item>
        <lightning-layout-item size="12" padding="around-medium"> 
<lightning-button-group>
<lightning-button label="Add" icon-name="utility:add" icon:position="right"></lightning-button> 
<lightning-button label="Subtract" icon-name="utlity:dash"  icon:position="right"></lightning-button>
<lightning-button label="Multiply" icon-name="utlity:close" icon:position="right"></lightning-button>
<lightning-button label="Divide" icon-name="utlity:magicwand" icon:position="right"></lightning-button>
</lightning-button-group>
</lightning-layout-item>
<lightning-layout-item size="12"  padding="around-medium">
    <lightning-formated-text value={}></lightning-formated-text>
</lightning-layout-item>
</lightning-layout>
</lightning-card>
</template>
This should fix the issue.
 
RedSalesRedSales 

Hello,

 

I have a Picklist in which one of the fields is "Error". On a user changing form fields and choosing to choose a different picklist value I want a validation rule to check the previous value of the picklist field and to only allow certain values to be picked if previously at "Error".  I have tried the following.

 

OR(AND(PRIORVALUE(Request_Status__c)='Error' , Request_Status__c<>'Draft Request'),AND(PRIORVALUE(Request_Status__c)='Error' , Request_Status__c<>'Endorse'))

 

I receive an error as follows:

Error: Field Request_Status__c is a picklist field. Picklist fields are only supported in certain functions. Tell me more

 

The "Tell me More" link brings me to teh following article  https://avaya--c4rdev.cs12.my.salesforce.com/help/doc/user_ed.jsp?loc=help&target=tips_on_building_formulas.htm%23picklists_and_msps&section=Customizing

 

In which it states "

  • PRIORVALUE(Only in assignment rules, validation rules, workflow field updates, and workflow rules in which the trigger type is set to Every time a record is created or edited)"

I do want this to run though every time an edit occurs though so figured it should work.

 

Does anyone happen to know from looking at the above what I may be doing wrong and a way to get around this?

 

Thanks in advance.


Best Answer chosen by Admin (Salesforce Developers) 
klekle

Hi there,

 

Since you are using a picklist, you should use ISPICKVAL in your validation rule.  Also, you will need to rewrite your rule a little bit.  It looks like your rule is trying to say "If the previous value of Request_Status__c was Error, then the new value cannot be Draft or Endorse."  

 

If that is the case, your rule should look something like this:

 

OR(
AND(
ISPICKVAL(PRIORVALUE(Request_Status__c),"Error"), NOT(ISPICKVAL(Request_Status__c,"Draft Request"))
),

AND(
ISPICKVAL(PRIORVALUE(Request_Status__c),"Error"), NOT(ISPICKVAL(Request_Status__c,"Endorse")))

)

 

I hope this helps.

 

Kemi

Francois CombeauFrancois Combeau 
1) I used use Module3RegistrationHandler.cls as registration handler.
2) I selected Google as login capability for Partners ( cf screenshot below)
However, the challenge fails with the following message :
Challenge Not yet complete... here's what's wrong:  Could not find a login to your community using Google.
Anybody can help ?
Thanks :-)
"Login & Registration" page
Best Answer chosen by Francois Combeau
SandhyaSandhya (Salesforce Developers) 
Hi Francois Combeau,

Check if you can log into the community using Google sign on the login page.

And also please consider this point in the same trailhead unit.

From Setup, enter All Communities in the Quick Find box, then select All Communities and click Manage next to the Customers community.
Select Administration, then Login & Registration and you see that Google is now an option.

Select Google and click Save.
To confirm your change, return to your private (incognito) browser and reload the login page. Check that the Google icon appears on the login page.

Hope this helps you!

Please accept my solution as Best Answer if my reply was helpful. It will make it available for other as the proper solution.

Thanks and Regards
Sandhya

 
Rohini Chaudhary 14Rohini Chaudhary 14 
Apex Class:
public with sharing class ChangeOpptyOwnerCtrl {
    private string oppId;
    public Opportunity oppobj {get;set;}
    public boolean isErrInSave {get;set;}
    
    public ChangeOpptyOwnerCtrl(ApexPages.StandardController ctrl){
        oppId = ApexPages.currentPage().getParameters().get('oppId');
        if(oppId != null)
            oppobj = [Select id, Name, OwnerId from Opportunity where id =: oppId limit 1];
    }
    
    public void saveOwner(){
        isErrInSave = false;
        try{
            if(oppobj != null)
                update oppobj;
        }catch(Exception e){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error , e.getMessage()));
            isErrInSave = true;
        }
    }
}


TestClass:

@isTest
public with sharing class ChangeOpptyOwnerCtrlTest {
    @testSetup
    static void setupTestData(){
        Account acc = TestUtility.createAccount('Test A');
        insert acc;
        Opportunity opp = TestUtility.createOpportunity('@test opp', Date.today(), 'To be Invoiced', acc.id);
        opp.Follow_up_Date__c = date.today();
        insert opp;
    }
    
    testmethod static void saveOwnerTest(){
        Opportunity opp = [Select id from Opportunity limit 1];
        test.startTest();
        
        Test.setCurrentPageReference(new PageReference('Page.ChangeOpptyOwnerPage'));
        System.currentPageReference().getParameters().put('oppId',opp.id);        
        ApexPages.StandardController sc = new ApexPages.StandardController(opp);
        ChangeOpptyOwnerCtrl ctrlObj = new ChangeOpptyOwnerCtrl(sc);
        
        ctrlObj.saveOwner();
        
        test.stopTest();
        
    }
    
}



can any one help me to cover catch(Exception e) lines
Best Answer chosen by Rohini Chaudhary 14
Maharajan CMaharajan C
Rohini, Please mark the best Answer to close this thread...
Li LeeLi Lee 
We use Salesforce Manufacturing Cloud for our business. We create a VF page show SalesAgreementProductSchedule record and edit those records.
To get and update records, we use JavaScript Remoting.During test, we found follow weird behavior in Salesfoce.
If we send SalesAgreementProductSchedule like { PlannedQuantity: 48, ID: 0YC8b0000008SDiGAM }, Salesforce Database.update throw error and we can not update this record. But if we put ID at first field in record like { ID: 0YC8b0000008SDiGAM, PlannedQuantity: 48 } we can success update this record.
I want to ask you why cause this behavior? Is there any document about it?
Best Answer chosen by Li Lee
Li LeeLi Lee
Hi, after we research more document we found solution in Salesforce Document: https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_Schema_SObjectType.htm

In this document has follow content:

User-added image
So we change our code as follow:
if (hasId) {
    newSObject(id);
} else { 
    newSObject();
}
Best Answer chosen by Sindhuja Sundarasudhan
PriyaPriya (Salesforce Developers) 
Hi sindhuja,

Please follow below

Create a report with Report type as "Users with Volunteer Shift Worker Records".
 
Your report must include the below columns:
 
Volunteer Organisation
 
Shift Hours (Note - This displays the records with SUM by default)
 
Step 1: Group by rows in 'Volunteer Organisation'
 
Step 2: Click on the arrow besides 'Volunteer Organisation' and select Sort by "Sum of Shift Hours" (This will display data as per sum of shift hours in ascending order)
 
Step 3: Click on the arrow besides 'Volunteer Organisation and select "Sort Descending" option.
 
P.S Ensure details, row counts and sub totals are off.
 
Hope this helps! 

Kindly mark it as the best answer if it helps.

Regards,
Ranjan
Chamil MadusankaChamil Madusanka 

HI All,

 

How to create a fomula field for my age field ? It will be calculated by using the Date_of_Birth__c field. I have a fomula.

 

IF(MONTH(TODAY())>MONTH(DOB_API),YEAR(TODAY())-YEAR(DOB_API),IF(AND(MONTH(TODAY())=MONTH(DOB_API),DAY(TODAY())>=DAY(DOB_API)),YEAR(TODAY())-YEAR(DOB_API),(YEAR(TODAY())-YEAR(DOB_API))-1))  

 That's from Ankit's blog. But I don't know how to use it and where to use it.

 

Thanks in Advance

Best Answer chosen by Admin (Salesforce Developers) 
Shashikant SharmaShashikant Sharma

Yes thats a correct formula , you can use above

If you want to go for smaller formula

 

Use this one : From http://forceschool.blogspot.com/2011/06/age-calculation-formula.html

 

IF(ISNULL(DOB__c) , DOB__c , FLOOR((TODAY()-DOB__c +1)/365.2425))

 Now to your question how to use it.

 

1) Create a formula field return type Integer

2) Use any of the formula , replace your date field API Name with DOB__c

 

Then you will see this Calculated Age in your formula field.

Celeste Streeter 7Celeste Streeter 7 
Hi,
I am trying to create an alert on a specific date field on an object that is time-based related. 

The issue is that both Process Builder and WorkFlow only fire when an object is updated or created, but not when a date becomes Today (naturally, without editing or creating the object's fields).

Here are my 3 separate use cases (each needs its own solution, but has the same problem):
1. On a custom object called "Project" we have a date-field called KICKOFF DATE.  When the date becomes today, we want an email alert to send out a reminder that today is kickoff date for this project.
2. When an Opp is in Stage 1 and it's Age = 60 days, we want to send an email alert that the Opportunity is 60 days old (from created date) and is in stage 1.
3. When an Opportunity is approaching the Close Date and is in a lower Stage, we want an alert to fire that says warns it is approaching.
So now I think I need a trigger to help fire this in Process Builder. 

Anybody ever had this need before or accomplished this?
Best Answer chosen by Celeste Streeter 7
Abhishek BansalAbhishek Bansal
Hi Celeste,

You can simply achieve this bys using a workflow rule. You can set the criteria as TRUE if you always want to execute this. You can add a time dependent workflow action which will be executed 0 days after KICKOFF Date.

Let me know if you need any help in setting up this worklflow rule.

Thanks,
Abhishek Bansal.
Gmail: abhibansal2790@gmail.com
Skype: abhishek.bansal2790