{"record":{"id":"a37ce09a2428de60","repo":"restsharp/RestSharp","slug":"error-occured-while-deserializing-the-response","errorCode":null,"errorMessage":"Error occured while deserializing the response","messagePattern":"Error occured while deserializing the response","errorType":"exception","errorClass":"DeserializationException","httpStatus":null,"severity":"error","filePath":"src/RestSharp/Serializers/RestSerializers.cs","lineNumber":52,"sourceCode":"\n    internal async ValueTask<RestResponse<T>> Deserialize<T>(RestRequest request, RestResponse raw, ReadOnlyRestClientOptions options, CancellationToken cancellationToken) {\n        var response = RestResponse<T>.FromResponse(raw);\n\n        try {\n            await OnBeforeDeserialization(raw, cancellationToken).ConfigureAwait(false);\n#pragma warning disable CS0618 // Type or member is obsolete\n            request.OnBeforeDeserialization?.Invoke(raw);\n#pragma warning restore CS0618 // Type or member is obsolete\n            response.Data = DeserializeContent<T>(raw);\n        }\n        catch (Exception ex) {\n            if (options.ThrowOnAnyError) throw;\n\n            if (options.FailOnDeserializationError || options.ThrowOnDeserializationError) response.ResponseStatus = ResponseStatus.Error;\n\n            response.AddException(ex);\n\n            if (options.ThrowOnDeserializationError) throw new DeserializationException(response, ex);\n        }\n\n        return response;\n    }\n   \n    static async ValueTask OnBeforeDeserialization(RestResponse response, CancellationToken cancellationToken) {\n        if (response.Request.Interceptors == null) return;\n\n        foreach (var interceptor in response.Request.Interceptors) {\n            await interceptor.BeforeDeserialization(response, cancellationToken).ConfigureAwait(false);\n        }\n    }\n\n    /// <summary>\n    /// Deserialize the response content into the specified type\n    /// </summary>\n    /// <param name=\"response\">Response instance</param>\n    /// <typeparam name=\"T\">Deserialized model type</typeparam>","sourceCodeStart":34,"sourceCodeEnd":70,"githubUrl":"https://github.com/restsharp/RestSharp/blob/6a5082169257438cd085f822f050d93256a8e499/src/RestSharp/Serializers/RestSerializers.cs#L34-L70","documentation":"When ThrowOnDeserializationError is enabled and deserializing the response body into T throws, RestSharp wraps the original exception in a DeserializationException (message 'Error occured while deserializing the response'). Without that option, the error is captured on the response (ResponseStatus.Error, response.ErrorException) and not thrown. With ThrowOnAnyError, the original exception propagates directly instead.","triggerScenarios":"Calling ExecuteAsync<T> with options.ThrowOnDeserializationError = true where the response content cannot be deserialized into T (schema mismatch, malformed JSON/XML, wrong content type, circular references, missing parameterless constructor).","commonSituations":"API returning an error page (HTML) instead of expected JSON; response schema changed; target type T lacks a parameterless constructor or has non-serializable members; content type not matching any registered deserializer.","solutions":["Inspect the DeserializationException.InnerException and the raw response.Content to find the deserialization failure cause.","Verify the target type T is serializable (parameterless constructor, public settable properties, compatible types).","If the server can return errors, first call ExecuteAsync (non-generic) and check IsSuccessful/StatusCode before deserializing, or handle the exception.","If you prefer non-throwing behavior, leave ThrowOnDeserializationError false and inspect response.ErrorException / ResponseStatus instead.","Register a deserializer that supports the response's actual content type."],"exampleFix":"// before\nvar resp = await client.ExecuteAsync<MyModel>(req); // throws DeserializationException\n\n// after (option A: inspect raw first)\nvar raw = await client.ExecuteAsync(req);\nif (!raw.IsSuccessful) HandleError(raw);\nelse {\n    var model = client.Serializers.DeserializeContent<MyModel>(raw);\n}\n// after (option B: tolerant options)\nvar options = new RestClientOptions(url) { ThrowOnDeserializationError = false };","handlingStrategy":"try-catch","validationCode":"// Validate response shape before deserializing when content is untrusted\nvar raw = await client.ExecuteAsync(req);\nif (!raw.IsSuccessful || string.IsNullOrWhiteSpace(raw.Content)) return;\nif (raw.ContentType?.Contains(\"json\") is false) return; // not the expected type","typeGuard":null,"tryCatchPattern":"try {\n    return await client.ExecuteAsync<T>(request, ct);\n}\ncatch (DeserializationException ex) {\n    logger.LogError(ex.InnerException, \"Failed to deserialize: {Content}\", ex.Response.Content);\n    throw;\n}","preventionTips":["Confirm the target type T has a parameterless constructor and serializable properties.","Check IsSuccessful and Content/ContentType before deserializing untrusted responses.","Set ThrowOnDeserializationError=false and inspect response.ErrorException if you prefer non-throwing flow.","Keep the registered deserializer matched to the server's content type."],"tags":["deserialization","response","serialization","exception","configuration"],"backgroundTag":null,"analyzedSha":"6a5082169257438cd085f822f050d93256a8e499","analyzedAt":"2026-08-13T20:38:25.807Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}