When working on DML operation in salesforce from Apex class developer might miss the security permissions that are assigned to different users through profiles, permission sets, sharing rules etc. This can lead to an exception. In this blog we will just see the solution for trailhead module for PD-1 certification. I will cover more details about stripInaccessible feature in a separate blog.

Get Hands-on With Field- and Object-Level Security and Safe Navigation Operator

global with sharing class ApexSecurityRest {
    global static Contact doGet() {
        Id recordId = RestContext.request.params.get('id');
        Contact result;
        if (recordId == null) {
            throw new FunctionalException('Id parameter is required');
        List<Contact> results = [SELECT id, Name, Title, Account.Name FROM Contact WHERE Id = :recordId];
        SObjectAccessDecision securityDecision = Security.stripInaccessible(AccessType.READABLE, results);
            result = (Contact)securityDecision?.getRecords()[0];
        	result.Description = result?.Account?.Name;
            throw new SecurityException('You don\'t have access to all contact fields required to use this API');
        return result;
    public class FunctionalException extends Exception{}
    public class SecurityException extends Exception{}

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s