JamesNK/Newtonsoft.Json · critical · InvalidOperationException

Could not clear error context. Error context is already null

Error message

Could not clear error context. Error context is already null.

What it means

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.

Source

Thrown at Src/Newtonsoft.Json/Serialization/JsonSerializerInternalBase.cs:113

        {
            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);

            if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Error && !errorContext.Traced)
            {
                // only write error once
                errorContext.Traced = true;

                // kind of a hack but meh. might clean this up later
                string message = (GetType() == typeof(JsonSerializerInternalWriter)) ? "Error serializing" : "Error deserializing";
                if (contract != null)
                {

View on GitHub (pinned to 4f73e74372)

Solutions

  1. Simplify or remove custom [OnError] / JsonSerializerSettings.Error handlers that may re-enter the serializer.
  2. Ensure binding redirects route all assemblies to a single consistent Json.NET version.
  3. Upgrade Json.NET to the latest version to pick up error-context fixes.
  4. Reproduce minimally and report if it occurs with stock settings and no custom error handlers.

Example fix

// before: error handler that re-enters serializer, corrupting context
settings.Error += (s, e) => {
    JsonConvert.SerializeObject(e.CurrentObject); // re-entry -> 228
};
// after: handler only marks handled
settings.Error += (s, e) => { e.ErrorContext.Handled = true; };
Defensive patterns

Strategy: validation

Try / catch

try { JsonConvert.DeserializeObject<T>(json, settings); }
catch (InvalidOperationException ex) when (ex.Message.Contains("Could not clear error context")) {
    logger.Error(ex, "error-context invariant violation; remove re-entrant error handlers."); throw;
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of JamesNK/Newtonsoft.Json@4f73e74372 (2026-08-07). Data as JSON: /api/errors/c4fb632ac6291dea. Report an issue: GitHub.