using System.Text.Json; using System.Text.Json.Serialization; using AnthropicClient.Models; namespace AnthropicClient.Json; class ErrorConverter : JsonConverter { public override Error Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { using var jsonDocument = JsonDocument.ParseValue(ref reader); var root = jsonDocument.RootElement; var type = root.GetProperty("type").GetString(); return type switch { ErrorType.InvalidRequestError => JsonSerializer.Deserialize(root.GetRawText(), options)!, ErrorType.AuthenticationError => JsonSerializer.Deserialize(root.GetRawText(), options)!, ErrorType.PermissionError => JsonSerializer.Deserialize(root.GetRawText(), options)!, ErrorType.NotFoundError => JsonSerializer.Deserialize(root.GetRawText(), options)!, ErrorType.RateLimitError => JsonSerializer.Deserialize(root.GetRawText(), options)!, ErrorType.ApiError => JsonSerializer.Deserialize(root.GetRawText(), options)!, ErrorType.OverloadedError => JsonSerializer.Deserialize(root.GetRawText(), options)!, _ => throw new JsonException($"Unknown error type: {type}") }; } public override void Write(Utf8JsonWriter writer, Error value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, value, value.GetType(), options); } }