Skip to main content

Use of JSON serialization of exceptions

Apex API 63.0 prevents JSON serialization of exception types, causing System.JSONException runtime errors when serializing built-in or custom exceptions.

David Martin avatar
Written by David Martin
Updated yesterday

Overview

Starting from API version 63.0, Apex no longer supports JSON serialization of custom exception types and most built-in exceptions. Attempting to serialize an exception, either directly or as part of an object, now always throws aSystem.JSONException at runtime: Type unsupported in JSON: MyException.

This behavior is versioned. In API version 62.0 and earlier, exception types could be serialized, but the serialization was incomplete and triggered unexpected exception errors or sometimes failed, rather than always failing as it does now.

Clayton classifies this as an Error because these issues represent a breaking change that will cause existing code using JSON.serialize() on exceptions to fail in API version 63.0 and later, directly impacting application stability. They should be prioritized for fixing as soon as possible and also act as blockers for pull requests.

Why This Matters

The breaking change in JSON serialization of exceptions can lead to:

  • Runtime Errors and Application Crashes: Code that previously relied on JSON.serialize() for exception objects (even if inconsistently) will now consistently throw a System.JSONException at runtime in API version 63.0 and later, leading to application failures.

  • Unpredictable Behavior: In API version 62.0 and earlier, the inconsistent serialization of exceptions could lead to unexpected behavior or loss of critical information when exceptions were serialized, making debugging and error analysis difficult.

  • Deployment Blockers: Code that uses this unsupported serialization pattern might fail validation or deployment when targeting API version 63.0 or higher.

  • Increased Technical Debt: Relying on or attempting to fix code that uses deprecated serialization patterns for exceptions adds technical debt, requiring refactoring to adopt supported error reporting mechanisms.

  • Debugging Challenges: While the new behavior is consistent (always fails), previously it could fail randomly, making root cause analysis more difficult.

What Triggers This Rule

This rule flags Apex code that attempts to serialize an Exception object (or any of its subclasses, including custom exceptions) using the JSON.serialize() or JSON.serializePretty() methods. Starting from API version 63.0, Salesforce explicitly disallows the JSON serialization of exceptions, causing a System.JSONException at runtime.

The rule (ApexJsonSerializeException) specifically looks for calls to these JSON serialization methods where the argument being serialized is an instance of Exception or a type that inherits from Exception.

Example of Code That Will Trigger This Rule:

Any Apex code that attempts to pass an Exception object (or any subclass) directly to JSON.serialize or JSON.serializePretty will trigger this rule.

public static String serializeMyObject() {
try {
// Simulate an error
Integer i = 1 / 0; // This will throw a System.MathException
return 'No error';
} catch (Exception e) {
// ❌ This line will trigger the rule because 'e' is an Exception object
return JSON.serialize(e);
}
}

public static String serializeCustomException() {
try {
throw new MyCustomException('Custom error occurred!');
} catch (MyCustomException e) {
// ❌ This line will trigger the rule because MyCustomException extends Exception
return JSON.serializePretty(e);
}
}

// Custom Exception Class (definition typically in a separate file or within the same class)
public class MyCustomException extends Exception {}

Recommended Safeguards

To ensure compatibility and robust error reporting:

  • Avoid Direct Serialization of Exceptions: Do not directly use JSON.serialize() on Exception objects or custom exception types in Apex code.

  • Extract Relevant Exception Information: Instead of serializing the entire exception object, manually extract and serialize only the necessary information from the exception (e.g., e.getMessage(), e.getStackTraceString(), e.getTypeName(), e.getCause()).

  • Create Custom Error Objects: Define a simple, serializable Apex class to represent error details. Populate instances of this class with relevant exception information and then serialize these custom error objects.

  • Upgrade API Versions: Ensure your Apex classes are updated to API version 63.0 or later to explicitly adopt this new behavior. This helps ensure that your code is developed and tested against the most current platform rules.

  • Thorough Testing: After refactoring code that previously serialized exceptions, perform comprehensive unit and integration tests to ensure that error handling and reporting mechanisms function as expected.

  • Consult Documentation: Refer to official Salesforce documentation on Apex JSON serialization and exception handling for the most up-to-date best practices.

Summary

Starting from API version 63.0, Apex no longer supports JSON serialization of custom exception types and most built-in exceptions. Attempting to serialize an exception, directly or as part of an object, now always triggers a runtime error. This is an Error because it's a versioned breaking change that will cause previous inconsistent serialization attempts to now consistently fail at runtime. Clayton detects instances where JSON.serialize() is used directly on exception objects, guiding developers to extract and serialize relevant exception data or use custom error objects to maintain application stability and ensure robust error reporting.


Resources

Did this answer your question?