All articles

Platform

Invalid conversion from runtime type in Apex

Diagnose unsafe Apex casts, validate generic inputs and parse JSON according to its actual shape before business processing.

A cast can compile and still fail when the object arrives at runtime. The declared Object type tells you little about the value inside it.

A cast asserts a compatible type; it doesn’t transform unrelated objects. If a generic handler receives a Contact, casting it to Account won’t create an Account with matching fields. Salesforce’s casting guide describes compatible class relationships and the instanceof check.

Validate before narrowing

For a handler that accepts an SObject, check its object type before using object-specific fields. This illustrative fragment assumes recordValue is an input variable:

if (recordValue != null &&
    recordValue.getSObjectType() == Account.SObjectType) {
    Account accountRecord = (Account) recordValue;
    // Process the Account using an explicit field contract.
} else {
    // Return or raise the handler's documented invalid-input result.
}

If only Accounts are valid, a typed parameter is usually clearer than a generic one. Use a broad interface when the business operation supports multiple types, with separate handling for each supported type.

Also distinguish a null value from an incompatible value. A permissive null path must not accidentally approve a required input that was never supplied.

Treat JSON shape as part of the API contract

JSON.deserializeUntyped returns generic values. An object-shaped response and an array-shaped response require different handling. A successful HTTP response may also carry an error object instead of the expected result array.

Validate the root shape, required keys and value types before entering the business operation. For a stable schema, a typed request or response class makes the expected structure easier to review. Deserialization alone still doesn’t establish that a required value is meaningful or authorized.

Avoid using serialization and deserialization as a general-purpose cast between unrelated business objects. Explicit field mapping makes conversions visible, including what happens to missing values, unexpected fields and numeric precision.

Test the boundary with different response shapes

Keep fixtures for a valid object, a valid array when supported, null, an error response and the wrong primitive type. Include a missing required key and a number outside the business range.

Return an actionable integration error without echoing the entire payload to logs or to an agent. Record a correlation ID and the failed validation step. A caller should know that parsing failed, rather than receiving a partially populated object that proceeds to DML.

The right repair is usually at the boundary that accepted ambiguous input. Fixing the cast deep in the processing code leaves every later consumer to rediscover the same uncertainty.

Keep reading

All articles