function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Amit Karlekar 4Amit Karlekar 4 

How To Display Custom Error Message?

Trigger Scenario:
Write a Trigger on the Account and Check Only Student Admin Profile Users Should Be Able to Delete an Account.

For the above scenario, I have written the following two types of handler classes.

Type 1: It Shows the Custom Error
public class PracticeHandlerClass {

 

    public static void practiceMethod(List<Account> accList) {

            for(Account acc : accList) {

                if(UserInfo.getProfileId() != 'Student Admin') {

                acc.addError('User Not Allowed To Delete The Record');

            }

        }

    }

}

-----------------------------------

Type 2: It Doesn't Show the Custom Error

public class PracticeHandlerClass {

    

    public static void practiceMethod(List<Account> accList) {

        Profile userProfile = [SELECT Id, Name FROM Profile WHERE Name = 'Student Administrator'];

        

        if(userProfile != null && UserInfo.getProfileId() != userProfile.Id) {

            for(Account acc : accList) {

                acc.addError('User Not Allowed To Delete The Record', 'CustomError');

            }

        }

    }

}

Even the 2nd type shows the error but, not the custom error message. I want to understand why?

What would be the correct code that will display the custom error message?

AshwiniAshwini (Salesforce Developers)