JamesNK/Newtonsoft.Json · critical · InvalidOperationException
Current error context error is different to requested error.
Error message
Current error context error is different to requested error.
What it means
Thrown by JsonSerializerInternalBase.GetErrorContext when an error context is already stored (_currentErrorContext != null) but its stored Error does not reference-identity-match the Exception being reported now. This is an internal invariant violation indicating overlapping/nested error handling, not a user data error.
Source
Thrown at Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs:103
{
NullValueHandling resolvedNullValueHandling =
property.NullValueHandling
?? containerContract?.ItemNullValueHandling
?? Serializer._nullValueHandling;
return resolvedNullValueHandling;
}
private ErrorContext GetErrorContext(object? currentObject, object? member, string path, Exception error)
{
if (_currentErrorContext == null)
{
_currentErrorContext = new ErrorContext(currentObject, member, path, error);
}
if (_currentErrorContext.Error != error)
{
throw new InvalidOperationException("Current error context error is different to requested error.");
}
return _currentErrorContext;
}
protected void ClearErrorContext()
{
if (_currentErrorContext == null)
{
throw new InvalidOperationException("Could not clear error context. Error context is already null.");
}
_currentErrorContext = null;
}
protected bool IsErrorHandled(object? currentObject, JsonContract? contract, object? keyValue, IJsonLineInfo? lineInfo, string path, Exception ex)
{
ErrorContext errorContext = GetErrorContext(currentObject, keyValue, path, ex);View on GitHub (pinned to 4f73e74372)
Solutions
- Audit any [OnError] handlers and OnErrorAttribute methods: ensure they do not perform work that can throw, and do not re-enter serialization.
- Inside an OnError handler, set ErrorEventArgs.ErrorContext.Handled = true and return cleanly without serializing nested objects.
- Update Json.NET to the latest patch release, as error-context handling has seen fixes.
- If still reproduced with no custom error handlers, file a minimal repro to the Json.NET project.
Example fix
// before: OnError handler that re-serializes and throws
[OnError]
internal void OnErr(StreamingContext ctx, ErrorEventArgs e) {
var rescue = JsonConvert.SerializeObject(e.CurrentObject); // may throw -> 227
}
// after: handler stays side-effect-free
[OnError]
internal void OnErr(StreamingContext ctx, ErrorEventArgs e) {
e.ErrorContext.Handled = true;
} Defensive patterns
Strategy: validation
Validate before calling
static void CheckNoOnError(Type t) { if (t.GetMethods().Any(m => m.GetCustomAttributes(true).Any(a => a.GetType().Name == "OnErrorAttribute"))) { /* verify handler is side-effect free */ } } Try / catch
try { JsonConvert.SerializeObject(obj); }
catch (InvalidOperationException ex) when (ex.Message.Contains("Current error context error is different")) {
logger.Error(ex, "nested/overlapping error handling; audit [OnError] handlers."); throw;
} Prevention
- Keep [OnError] and Error handlers side-effect free.
- Never re-enter Serialize/Deserialize inside an error handler.
- Always set ErrorContext.Handled in handlers and return promptly.
- Upgrade Json.NET to pick up error-context fixes.
When it happens
Trigger: Reached when two different exceptions are tracked as 'current' without the first being cleared first - e.g. an OnErrorAttribute handler or OnError callback itself triggers a second error before the original context is cleared. Generally a sign of recursive/overlapping error handling within Json.NET's internal pipeline.
Common situations: A custom OnErrorAttribute handler or JsonSerializerSettings.Error callback that itself performs serialization/deserialization that throws again; a converter that swallows an exception and re-throws inside the same frame; very rare and usually a library bug or a misbehaving custom error handler.
Related errors
- Could not clear error context. Error context is already null
- Wrapped ICollection<T> does not support indexer.
- Unexpected token when writing BSON: {0}
- Unexpected value type when writing binary: {0}
- CustomCreationConverter should only be used while deserializ
AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07).
Data as JSON: /api/errors/4c3db477493ae82e.
Report an issue: GitHub.