I am suffering with Salesforce apex LimitException issue. I am fetching thousands of records from few objects and putting it into the collection like Map. Now I have a requirement to generate JSON for same records which will be used for mobile devices to download data from Salesforce. When I tried to serialize those records by using System.JSON.Serialize() method; it is generating a huge JSON string and I am getting System.LimitException error because there will be more memory required than available space. I tried to catch that issue using try/catch block but here is a reference available which says that System.LimitException can’t be caught by Catch block. Referral URL:


I know that we can check heap size limit through Limits.getHeapSize() method. But is there any work around so that I can handle this issue from apex side. A code sample or some reference in this regard would be highly appreciated. Thanks in advanced.


You're receiving this error because you're trying to process and store too much data through a method and architecture that's not designed to do this. Specially if you intend to use this for data download or synchronization you have to consider that if you're hitting a heap limit, you're likely going to have usability issues for your mobile users too.

Please consider an alternative way of processing and sending over this data. Consider segmenting your data and implement some polling, pagination or lazy loading algorithm to get your data across.

Governor limits are not something you want to attempt to "work around", they usually are an indication that something in your design is flawed and you should attempt to reflect on this.

  • Thank you for your replies. I solved this issue, instead of serializing data in my side I am returning collection from method. And also checking some range for heap size. Sep 29 '14 at 7:15
  • If you post that as an answer, possibly including some code this becomes more discoverable for others running into the same problem. You'd also be able to accept it as answer to your question, indicating that this question has been resolved. Sep 29 '14 at 7:24

Another alternative approach could be,

That you break your JSON Construction, into multiple parts, such as :

  1. Create Multiple JSON Files for different data stores
  2. Append to the same JSON File in multiple steps. (You can use attachment / document object to store and retrieve the JSON to append to it.)

One of the alternatives is to also Batch Apex to construct the JSON Data.


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.