0

How to return an error msg, if boxes are more than 1000 and we can't return this list (return null + msg)? We need to do that with if or with try catch? Or we can try both variants?

@HttpGet
global static List<Box__c> getBox(){
    RestRequest req = RestContext.request;
    String boxId = req.params.get('Id');

    List<Box__c> boxList;
    boxList = [SELECT Id, Title__c 
               FROM Box__c
               WHERE Id =: boxId
               LIMIT 1000];
    return boxList;
}
  • One of the strongest coding axioms where I work is that we never return a null collection. I advise against doing so. – Adrian Larson Oct 5 '18 at 20:23
7

First, you have to create wrapper for response class, so that you can tell is it successful request, or not. Second, you can query 1001 records and if list of queried records is more than 1000, return response with error message

@HttpGet
global static GetBoxesResponse getBox(){
    RestRequest req = RestContext.request;
    String boxId = req.params.get('Id');
    List<Box__c> boxList = [
        select Id, Title__c 
        from Box__c
        where Id =: boxId
        limit 1001];
    GetBoxesResponse result = null; 
    if(boxList.size() > 1000){
        result = new GetBoxesResponse('Too many boxes');
    } else {
        result = new GetBoxesResponse(boxList);
    }
    return result;
}



global class GetBoxesResponse{
    global Boolean success {get; set;}
    global String message {get; set;}
    global List<Box__c> boxes {get; set;}

    global GetBoxesResponse(List<Box__c> boxes){
        this.success = true;
        this.boxes = boxes;
    }

    global GetBoxesResponse(String message){
        this.success = false;
        this.message = message;
    }
}

By the way, seems like you have something wrong in your logic, as query SELECT Id, Title__c FROM Box__c WHERE Id =: boxId can't return more then one record.

1

We can achieve it using if.

Get all the box records in a list - boxList

if(boxList.size() > 1000) {
   return null; // or return 'Error Message';
}

try - catch, is used to handle exceptions not for checks.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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