validateAndSerialize static method
Validates and attempts to serialize a value to JSON.
This is a convenience method that validates and then attempts JSON serialization to ensure the value is truly serializable.
Parameters:
value: The value to validate and serializekey: Optional key name for error messages
Throws:
- StateError if validation fails
- StateError if serialization fails
Returns: The JSON-encoded string representation of the value.
Implementation
static String validateAndSerialize(dynamic value, [String? key]) {
final path = key ?? 'root';
validate(value, path);
try {
return jsonEncode(value);
} catch (e) {
throw StateError(
'Failed to serialize value at path "$path": $e. '
'Type: ${value.runtimeType}.',
);
}
}