{"record":{"id":"c4fb632ac6291dea","repo":"JamesNK/Newtonsoft.Json","slug":"could-not-clear-error-context-error-context-is-al","errorCode":null,"errorMessage":"Could not clear error context. Error context is already null.","messagePattern":"Could not clear error context\\. Error context is already null\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"critical","filePath":"Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs","lineNumber":113,"sourceCode":"        {\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);\n\n            if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Error && !errorContext.Traced)\n            {\n                // only write error once\n                errorContext.Traced = true;\n\n                // kind of a hack but meh. might clean this up later\n                string message = (GetType() == typeof(JsonSerializerInternalWriter)) ? \"Error serializing\" : \"Error deserializing\";\n                if (contract != null)\n                {","sourceCodeStart":95,"sourceCodeEnd":131,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs#L95-L131","documentation":"Thrown by JsonSerializerInternalBase.ClearErrorContext when there is no current error context to clear (_currentErrorContext == null). Like 227, this is an internal invariant violation signalling mismatched get/clear calls in the error-handling pipeline rather than a problem with user data.","triggerScenarios":"The serializer's error pipeline calls ClearErrorContext after a successful error-handling cycle, but the context has already been nulled (double-clear). Caused by overlapping error-handling frames or re-entrant serialization that clears the context out of order.","commonSituations":"Custom OnErrorAttribute handlers that themselves invoke serialize/deserialize, converters that trigger error handling then swallow it, or library version mismatches across binding redirects that mix incompatible internal state machines.","solutions":["Simplify or remove custom [OnError] / JsonSerializerSettings.Error handlers that may re-enter the serializer.","Ensure binding redirects route all assemblies to a single consistent Json.NET version.","Upgrade Json.NET to the latest version to pick up error-context fixes.","Reproduce minimally and report if it occurs with stock settings and no custom error handlers."],"exampleFix":"// before: error handler that re-enters serializer, corrupting context\nsettings.Error += (s, e) => {\n    JsonConvert.SerializeObject(e.CurrentObject); // re-entry -> 228\n};\n// after: handler only marks handled\nsettings.Error += (s, e) => { e.ErrorContext.Handled = true; };","handlingStrategy":"validation","validationCode":null,"typeGuard":null,"tryCatchPattern":"try { JsonConvert.DeserializeObject<T>(json, settings); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"Could not clear error context\")) {\n    logger.Error(ex, \"error-context invariant violation; remove re-entrant error handlers.\"); throw;\n}","preventionTips":["Do not call Serialize/Deserialize from within an OnError handler.","Pin a single consistent Json.NET version via binding redirects.","Upgrade Json.NET to the latest patch.","Keep error handlers minimal: mark Handled and return."],"tags":["error-context","internal","onerror","serialization"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}