Saturday, 26 January 2013

Salesforce System Error: 1148877694-2467 (681892207) (681892207) when using JSON generator class in apex

Today i encountered a very interesting error when i was using JSON generator .The error said FATAL_ERROR System.UnexpectedException: Salesforce System Error: 1148877694-2467 (681892207) (681892207).

Looking into the error my first thing was to run through my code again and again .I referred the following documents on JSON generator class 



The code in my eyes look pretty simple and here is the exact snippet that was throwing the exception

JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartObject();
gen.writeNumberField('abc', 1.21);
gen.writeStringField('def', 'xyz');
String pretty = gen.getAsString();//This statement use at the end only .It ends the JSON 
System.debug('STRING JSON'+pretty);
gen.writeStartObject();
gen.writeStringField('def', 'xyz');
gen.writeEndObject();

After the line 6 (where i am printing the log )i have the following statement in my debug log 13:24:03:048 FATAL_ERROR System.UnexpectedException: Salesforce System Error: 1148877694-2467 (681892207) (681892207)

I decided to read the document again and discovered that the when i use the method getAsString method of JSON generator class the apex automatically closes the JSON and hence attempting to start writing the Object after closing generates an error .

Though this is simple issue but the error message is not caught properly in the salesforce backend .

So the conclusion is always using getAsString of JSON generator class should be practiced .

Never use it even for the debug statements.

This is one of the rare cases where error message is misleading.Hope this helps for people trying to google and find why the error is occuring when using JSON generator.

Just commmenting Line 5 and line 6 will resolve the issue.
Happy Coding !

Introducing Lightning Base Components

Lightning Base Components are great addition to the platform and in fact revolutionary .One of the concerns around lightning component ...