0

I have a VF page which is fired based on a custom button click from Case record's detail page. window.location = 'apex/onClickPage?Id={!Case.Id}';

In Apex controller class, I am getting the Id from the URL using: String caseUrlId = ApexPages.currentPage().getParameters().get('Id');

Based on the URL, I am querying Case object to get some field that are to be displayed on the VF page.

If a user deletes the Id from the URL, I am getting a page with error message: common.apex.runtime.impl.ExecutionException: Attempt to de-reference a null object. How can I use Try-Catch blocks to handle this:

If Id from the URL is deleted, I need to redirect the user to the Standard Salesforce Home page.

  • Do you have a code sample? What have you tried? – Sebastian Kessel Jun 16 '17 at 2:40
3

You can also just validate the Id parameter. There are a number of different ways. Here's one example. You can use this in a utility class.

For instance you can check if it's not null, if is an Id, if is the correct SObject type, and if it returns a query result. If this is false, redirect them.

Additional checks can be added for accessibility and even if the Id is the correct record type.

public static Boolean isValidParamId(String paramId, SObjectType soType) {
    Boolean isValid = false;
    if (paramId != null && paramId InstanceOf Id && ((Id)paramId).getSobjectType() == soType) {
        String soName = soType.getDescribe().getName();
        SObject[] records = Database.query('SELECT Id FROM ' + soName + ' WHERE Id = :paramId');
        isValid = !records.isEmpty() ? true : false;
    }
    return isValid;
}

If you are using the case SObject, you can use this as so.

isValidParamId(ApexPages.currentPage().getParameters().get('Id'), Case.SObjectType);
0

If you are using standardController then you can use controller.getRecord() no SOQL needed. You can try this

public class testCase{
String caseUrlId;
public testCase(){
 caseUrlId = ApexPages.currentPage().getParameters().get('Id');
 try{
 // caseUrlId<> NULL && caseUrlId <> '' can be added to if you want null check
 if(Id.valueOf(caseUrlId)){
   // your SOQL here.
 }
}
catch(Exception E){
// Exception handeling here
}

}

}

As you want to with try catch I showed in this way. You can use regEX and Id.getSObjectType() as well to check the object type. reference here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.