{"record":{"id":"4c3db477493ae82e","repo":"JamesNK/Newtonsoft.Json","slug":"current-error-context-error-is-different-to-reques","errorCode":null,"errorMessage":"Current error context error is different to requested error.","messagePattern":"Current error context error is different to requested error\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"critical","filePath":"Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs","lineNumber":103,"sourceCode":"        {\n            NullValueHandling resolvedNullValueHandling =\n                property.NullValueHandling\n                ?? containerContract?.ItemNullValueHandling\n                ?? Serializer._nullValueHandling;\n\n            return resolvedNullValueHandling;\n        }\n\n        private ErrorContext GetErrorContext(object? currentObject, object? member, string path, Exception error)\n        {\n            if (_currentErrorContext == null)\n            {\n                _currentErrorContext = new ErrorContext(currentObject, member, path, error);\n            }\n\n            if (_currentErrorContext.Error != error)\n            {\n                throw new InvalidOperationException(\"Current error context error is different to requested error.\");\n            }\n\n            return _currentErrorContext;\n        }\n\n        protected void ClearErrorContext()\n        {\n            if (_currentErrorContext == null)\n            {\n                throw new InvalidOperationException(\"Could not clear error context. Error context is already null.\");\n            }\n\n            _currentErrorContext = null;\n        }\n\n        protected bool IsErrorHandled(object? currentObject, JsonContract? contract, object? keyValue, IJsonLineInfo? lineInfo, string path, Exception ex)\n        {\n            ErrorContext errorContext = GetErrorContext(currentObject, keyValue, path, ex);","sourceCodeStart":85,"sourceCodeEnd":121,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs#L85-L121","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before: OnError handler that re-serializes and throws\n[OnError]\ninternal void OnErr(StreamingContext ctx, ErrorEventArgs e) {\n    var rescue = JsonConvert.SerializeObject(e.CurrentObject); // may throw -> 227\n}\n// after: handler stays side-effect-free\n[OnError]\ninternal void OnErr(StreamingContext ctx, ErrorEventArgs e) {\n    e.ErrorContext.Handled = true;\n}","handlingStrategy":"validation","validationCode":"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 */ } }","typeGuard":null,"tryCatchPattern":"try { JsonConvert.SerializeObject(obj); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"Current error context error is different\")) {\n    logger.Error(ex, \"nested/overlapping error handling; audit [OnError] handlers.\"); throw;\n}","preventionTips":["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."],"tags":["error-context","onerror","internal","serialization"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}