Download train.jsonl from SalutefaceAAC/api-error-resolution-pairs: direct link, hf CLI and curl.
- Browser
- Download file 93.7 kB
-
https://huggingface.co/datasets/SalutefaceAAC/api-error-resolution-pairs/resolve/main/train.jsonl
- Command line
-
hf download hf://datasets/SalutefaceAAC/api-error-resolution-pairs/train.jsonl
-
curl -L -o train.jsonl https://huggingface.co/datasets/SalutefaceAAC/api-error-resolution-pairs/resolve/main/train.jsonl
93.7 kB
| {"language": "rest", "library": "generic", "error_type": "content_negotiation", "error_message": "406 Not Acceptable", "broken_code": "GET /api/data\nAccept: text/html", "explanation": "The server only produces JSON; sending Accept: text/html returns 406.", "fixed_code": "GET /api/data\nAccept: application/json", "key_insight": "Match the Accept header to the media types the server advertises.", "tags": ["rest", "content-negotiation", "406"], "id": 1} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.slack.com/api/chat.postMessage\")", "explanation": "No timeout set on call to slack endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.slack.com/api/chat.postMessage\", timeout=5)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "slack"], "id": 2} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.slack.com/api/chat.postMessage\")", "explanation": "No timeout set on call to slack endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.slack.com/api/chat.postMessage\", timeout=10)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "slack"], "id": 3} | |
| {"language": "javascript", "library": "axios", "error_type": "cancel_request", "error_message": "CanceledError unhandled when navigating away", "broken_code": "const source = axios.CancelToken.source();\naxios.get(\"/slow-api\", { cancelToken: source.token });\nsource.cancel();", "explanation": "Cancellation throws a CanceledError that must be caught and handled.", "fixed_code": "const controller = new AbortController();\ntry {\n const resp = await axios.get(\"/slow-api\", { signal: controller.signal });\n process(resp.data);\n} catch (err) {\n if (!axios.isCancel(err)) throw err;\n}\n// to cancel: controller.abort();", "key_insight": "Use AbortController with axios (v1+) and filter cancellations with axios.isCancel(err).", "tags": ["axios", "cancel", "abort"], "id": 4} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\")", "explanation": "The mapbox API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Bearer {TOKEN}\"}\nresp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "mapbox"], "id": 5} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\")", "explanation": "The msgraph API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Bearer {TOKEN}\"}\nresp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "msgraph"], "id": 6} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\")", "explanation": "No timeout set on call to github endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\", timeout=60)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "github"], "id": 7} | |
| {"language": "python", "library": "requests", "error_type": "stream_large_response", "error_message": "MemoryError downloading large file", "broken_code": "resp = requests.get(\"https://example.com/large-file.zip\")\nwith open(\"large-file.zip\", \"wb\") as f:\n f.write(resp.content)", "explanation": "resp.content loads the entire response into memory. For large files, stream the response.", "fixed_code": "resp = requests.get(\"https://example.com/large-file.zip\", stream=True)\nwith open(\"large-file.zip\", \"wb\") as f:\n for chunk in resp.iter_content(chunk_size=8192):\n f.write(chunk)", "key_insight": "Use stream=True and iter_content() to download large files without loading them into memory.", "tags": ["streaming", "download", "memory"], "id": 8} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.slack.com/api/chat.postMessage\")", "explanation": "The slack API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Token {API_KEY}\"}\nresp = requests.get(\"https://api.slack.com/api/chat.postMessage\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "slack"], "id": 9} | |
| {"language": "python", "library": "stripe", "error_type": "expand_nested", "error_message": "AttributeError: PaymentIntent has no attribute 'customer' \u2014 got string ID", "broken_code": "intent = stripe.PaymentIntent.retrieve(\"pi_...\")\nprint(intent.customer.email) # intent.customer is a string ID", "explanation": "By default Stripe returns nested object IDs as strings. Use expand= to include full objects.", "fixed_code": "intent = stripe.PaymentIntent.retrieve(\"pi_...\", expand=[\"customer\"])\nprint(intent.customer.email)", "key_insight": "Use expand=['nested.field'] to retrieve full objects; by default Stripe returns only IDs.", "tags": ["stripe", "expand", "nested-objects"], "id": 10} | |
| {"language": "python", "library": "anthropic", "error_type": "system_in_messages", "error_message": "Response ignores instructions in messages role=system", "broken_code": "messages = [{\"role\": \"system\", \"content\": \"You are a concise assistant.\"}, {\"role\": \"user\", \"content\": \"Explain quantum computing.\"}]\nresp = client.messages.create(model=\"claude-opus-4-7\", max_tokens=512, messages=messages)", "explanation": "Anthropic Messages API has a top-level system parameter \u2014 not a message with role='system'.", "fixed_code": "resp = client.messages.create(\n model=\"claude-opus-4-7\",\n max_tokens=512,\n system=\"You are a concise assistant.\",\n messages=[{\"role\": \"user\", \"content\": \"Explain quantum computing.\"}],\n)", "key_insight": "Pass system instructions via the top-level system= parameter, not as a message with role='system'.", "tags": ["anthropic", "system-prompt"], "id": 11} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\")", "explanation": "The github API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Bearer {TOKEN}\"}\nresp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "github"], "id": 12} | |
| {"language": "javascript", "library": "fetch", "error_type": "no_error_check", "error_message": "Silently receives 4xx/5xx without throwing", "broken_code": "const resp = await fetch(\"https://api.sendgrid.com/v3/mail/send\");\nconst data = await resp.json();", "explanation": "fetch() resolves even on HTTP errors from sendgrid. Status must be checked manually.", "fixed_code": "const resp = await fetch(\"https://api.sendgrid.com/v3/mail/send\");\nif (!resp.ok) throw new Error(`HTTP ${resp.status} from sendgrid`);\nconst data = await resp.json();", "key_insight": "fetch() only rejects on network failure; always check resp.ok for HTTP-level errors.", "tags": ["fetch", "error-handling", "sendgrid"], "id": 13} | |
| {"language": "python", "library": "boto3", "error_type": "s3_upload_large", "error_message": "EntityTooLarge: Your proposed upload exceeds the maximum allowed size", "broken_code": "s3.put_object(Bucket=\"mybucket\", Key=\"largefile.bin\", Body=large_bytes)", "explanation": "put_object has a 5 GB limit. Large files require multipart upload.", "fixed_code": "from boto3.s3.transfer import TransferConfig\nconfig = TransferConfig(multipart_threshold=8 * 1024 * 1024)\ns3.upload_file(\"largefile.bin\", \"mybucket\", \"largefile.bin\", Config=config)", "key_insight": "Use upload_file with TransferConfig(multipart_threshold=...) for files > 5 GB.", "tags": ["aws", "s3", "upload", "multipart"], "id": 14} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.stripe.com/v1/charges\")", "explanation": "The stripe API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Bearer {TOKEN}\"}\nresp = requests.get(\"https://api.stripe.com/v1/charges\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "stripe"], "id": 15} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\")", "explanation": "No timeout set on call to mapbox endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\", timeout=15)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "mapbox"], "id": 16} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.example.com/data\")\nprint(resp.json())", "explanation": "The request is missing authentication credentials. The API requires a Bearer token in the Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Bearer YOUR_TOKEN\"}\nresp = requests.get(\"https://api.example.com/data\", headers=headers)\nresp.raise_for_status()\nprint(resp.json())", "key_insight": "Always attach auth headers explicitly; requests does not add them automatically.", "tags": ["auth", "http", "401"], "id": 17} | |
| {"language": "python", "library": "boto3", "error_type": "region_missing", "error_message": "EndpointResolutionError: endpoint could not be resolved", "broken_code": "import boto3\nclient = boto3.client(\"bedrock-runtime\") # no region", "explanation": "Some AWS services (like Bedrock) require an explicit region.", "fixed_code": "import boto3\nclient = boto3.client(\"bedrock-runtime\", region_name=\"us-east-1\")", "key_insight": "Always specify region_name for regional AWS services; the SDK default may not support the service.", "tags": ["aws", "region", "boto3"], "id": 18} | |
| {"language": "go", "library": "net/http", "error_type": "http_status_not_checked", "error_message": "Silent error: 404 treated as success", "broken_code": "resp, _ := http.Get(\"https://api.example.com/users/99\")\ndefer resp.Body.Close()\nbody, _ := io.ReadAll(resp.Body)", "explanation": "HTTP status code is not checked; 404 or 500 responses are silently treated as success.", "fixed_code": "resp, err := http.Get(\"https://api.example.com/users/99\")\nif err != nil { log.Fatal(err) }\ndefer resp.Body.Close()\nif resp.StatusCode != http.StatusOK {\n log.Fatalf(\"unexpected status: %d\", resp.StatusCode)\n}\nbody, err := io.ReadAll(resp.Body)", "key_insight": "Always check resp.StatusCode after a successful Do/Get; network success != HTTP success.", "tags": ["go", "http", "error-handling"], "id": 19} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\")", "explanation": "No timeout set on call to mapbox endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\", timeout=60)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "mapbox"], "id": 20} | |
| {"language": "javascript", "library": "fetch", "error_type": "credential_cookies", "error_message": "Cookies not sent on cross-origin requests", "broken_code": "const resp = await fetch(\"https://api.example.com/profile\");", "explanation": "By default fetch does not send cookies for cross-origin requests.", "fixed_code": "const resp = await fetch(\"https://api.example.com/profile\", { credentials: \"include\" });\nif (!resp.ok) throw new Error(`HTTP ${resp.status}`);\nconst data = await resp.json();", "key_insight": "Set credentials: 'include' to send cookies cross-origin; also requires server CORS Allow-Credentials.", "tags": ["fetch", "cookies", "credentials", "cors"], "id": 21} | |
| {"language": "python", "library": "redis", "error_type": "cache_stampede", "error_message": "Cache stampede: all workers recompute on cache miss simultaneously", "broken_code": "val = r.get(\"expensive_result\")\nif val is None:\n val = compute_expensive_result()\n r.set(\"expensive_result\", val, ex=300)", "explanation": "Many workers miss simultaneously and all start computing, overloading the backend.", "fixed_code": "import time\nLOCK_KEY = \"expensive_result:lock\"\nval = r.get(\"expensive_result\")\nif val is None:\n if r.set(LOCK_KEY, \"1\", nx=True, ex=30):\n try:\n val = compute_expensive_result()\n r.set(\"expensive_result\", val, ex=300)\n finally:\n r.delete(LOCK_KEY)\n else:\n time.sleep(0.1)\n val = r.get(\"expensive_result\")", "key_insight": "Use a Redis SETNX lock to allow only one worker to recompute on cache miss; others wait or serve stale.", "tags": ["redis", "cache", "stampede", "locking"], "id": 22} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\")", "explanation": "The msgraph API requires authentication via X-API-Key header.", "fixed_code": "headers = {\"X-API-Key\": \"X-API-Key: {API_KEY}\"}\nresp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in X-API-Key header; requests does not add them automatically.", "tags": ["auth", "401", "msgraph"], "id": 23} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\")", "explanation": "No timeout set on call to msgraph endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\", timeout=10)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "msgraph"], "id": 24} | |
| {"language": "python", "library": "requests", "error_type": "json_body", "error_message": "415 Unsupported Media Type", "broken_code": "payload = {\"name\": \"alice\", \"role\": \"admin\"}\nresp = requests.post(\"https://api.example.com/users\", data=payload)", "explanation": "data= sends form-encoded body. The API expects JSON, so the Content-Type is wrong.", "fixed_code": "payload = {\"name\": \"alice\", \"role\": \"admin\"}\nresp = requests.post(\"https://api.example.com/users\", json=payload)\nresp.raise_for_status()", "key_insight": "Use json= not data= to send JSON; requests sets Content-Type automatically.", "tags": ["json", "content-type", "415"], "id": 25} | |
| {"language": "python", "library": "boto3", "error_type": "paginator_missing", "error_message": "Truncated results: only first 1000 S3 objects returned", "broken_code": "resp = s3.list_objects_v2(Bucket=\"mybucket\")\nobjects = resp[\"Contents\"]", "explanation": "list_objects_v2 returns at most 1000 objects. Use a paginator for buckets with more.", "fixed_code": "paginator = s3.get_paginator(\"list_objects_v2\")\nobjects = []\nfor page in paginator.paginate(Bucket=\"mybucket\"):\n objects.extend(page.get(\"Contents\", []))", "key_insight": "Use boto3 paginators for any list operation that may return more than 1000 results.", "tags": ["aws", "s3", "pagination"], "id": 26} | |
| {"language": "python", "library": "aiohttp", "error_type": "concurrent_requests", "error_message": "Sequential async calls \u2014 no performance gain", "broken_code": "async def fetch_all(urls):\n results = []\n for url in urls:\n resp = await session.get(url)\n results.append(await resp.json())\n return results", "explanation": "Sequential awaits defeat the purpose of async. Use asyncio.gather for concurrent requests.", "fixed_code": "async def fetch_all(urls, session):\n async def fetch_one(url):\n resp = await session.get(url)\n resp.raise_for_status()\n return await resp.json()\n return await asyncio.gather(*[fetch_one(url) for url in urls])", "key_insight": "Use asyncio.gather() to run independent async requests concurrently.", "tags": ["aiohttp", "async", "concurrent", "asyncio"], "id": 27} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\")", "explanation": "No timeout set on call to twilio endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\", timeout=5)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "twilio"], "id": 28} | |
| {"language": "python", "library": "google-auth", "error_type": "no_credentials", "error_message": "google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials", "broken_code": "import googleapiclient.discovery\nservice = googleapiclient.discovery.build(\"calendar\", \"v3\")", "explanation": "No Application Default Credentials found. Point to the service account key file explicitly.", "fixed_code": "from google.oauth2 import service_account\nimport googleapiclient.discovery\n\ncreds = service_account.Credentials.from_service_account_file(\n \"service-account-key.json\",\n scopes=[\"https://www.googleapis.com/auth/calendar.readonly\"],\n)\nservice = googleapiclient.discovery.build(\"calendar\", \"v3\", credentials=creds)", "key_insight": "Use service_account.Credentials.from_service_account_file() for server-side auth.", "tags": ["google", "auth", "service-account"], "id": 29} | |
| {"language": "python", "library": "requests", "error_type": "json_body", "error_message": "415 Unsupported Media Type", "broken_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://api.openai.com/v1/embeddings\", data=payload)", "explanation": "data= sends form-encoded body to openai-rest. Use json= for JSON requests.", "fixed_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://api.openai.com/v1/embeddings\", json=payload)\nresp.raise_for_status()", "key_insight": "Use json= not data= to send JSON; requests sets Content-Type automatically.", "tags": ["json", "content-type", "415", "openai-rest"], "id": 30} | |
| {"language": "python", "library": "requests", "error_type": "json_body", "error_message": "415 Unsupported Media Type", "broken_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://graph.microsoft.com/v1.0/me/messages\", data=payload)", "explanation": "data= sends form-encoded body to msgraph. Use json= for JSON requests.", "fixed_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://graph.microsoft.com/v1.0/me/messages\", json=payload)\nresp.raise_for_status()", "key_insight": "Use json= not data= to send JSON; requests sets Content-Type automatically.", "tags": ["json", "content-type", "415", "msgraph"], "id": 31} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.sendgrid.com/v3/mail/send\")", "explanation": "The sendgrid API requires authentication via X-API-Key header.", "fixed_code": "headers = {\"X-API-Key\": \"X-API-Key: {API_KEY}\"}\nresp = requests.get(\"https://api.sendgrid.com/v3/mail/send\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in X-API-Key header; requests does not add them automatically.", "tags": ["auth", "401", "sendgrid"], "id": 32} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\")", "explanation": "No timeout set on call to twilio endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\", timeout=30)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "twilio"], "id": 33} | |
| {"language": "python", "library": "requests", "error_type": "ssl_verify_false", "error_message": "requests.exceptions.SSLError: certificate verify failed", "broken_code": "resp = requests.get(\"https://internal-dev.example.com/api\", verify=False)", "explanation": "Disabling SSL verification is insecure. The dev server has a self-signed cert that should be trusted explicitly.", "fixed_code": "resp = requests.get(\"https://internal-dev.example.com/api\", verify=\"/path/to/dev-ca.crt\")\nresp.raise_for_status()", "key_insight": "Pass verify='/path/to/ca-bundle.crt' instead of verify=False to trust self-signed certs securely.", "tags": ["ssl", "security"], "id": 34} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\")", "explanation": "No timeout set on call to openai-rest endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\", timeout=30)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "openai-rest"], "id": 35} | |
| {"language": "java", "library": "okhttp", "error_type": "network_on_main_thread", "error_message": "NetworkOnMainThreadException on Android", "broken_code": "OkHttpClient client = new OkHttpClient();\nRequest request = new Request.Builder().url(\"https://api.example.com/data\").build();\nResponse response = client.newCall(request).execute();", "explanation": "Synchronous HTTP calls on Android main thread throw NetworkOnMainThreadException.", "fixed_code": "OkHttpClient client = new OkHttpClient();\nRequest request = new Request.Builder().url(\"https://api.example.com/data\").build();\nclient.newCall(request).enqueue(new Callback() {\n @Override public void onFailure(Call call, IOException e) { /* handle */ }\n @Override public void onResponse(Call call, Response response) throws IOException {\n try (ResponseBody body = response.body()) {\n String json = body.string();\n }\n }\n});", "key_insight": "Use .enqueue() for async HTTP on Android; never block the main thread with .execute().", "tags": ["java", "android", "okhttp", "main-thread"], "id": 36} | |
| {"language": "python", "library": "anthropic", "error_type": "prompt_caching", "error_message": "High latency on repeated identical system prompts", "broken_code": "resp = client.messages.create(\n model=\"claude-opus-4-7\",\n max_tokens=512,\n system=\"You are a helpful assistant. \" + LONG_CONTEXT,\n messages=messages,\n)", "explanation": "Large repeated system prompts incur full processing cost each time. Use prompt caching.", "fixed_code": "resp = client.messages.create(\n model=\"claude-opus-4-7\",\n max_tokens=512,\n system=[{\"type\": \"text\", \"text\": \"You are a helpful assistant. \" + LONG_CONTEXT, \"cache_control\": {\"type\": \"ephemeral\"}}],\n messages=messages,\n)", "key_insight": "Add cache_control: {type: ephemeral} to large static system prompt blocks to enable Anthropic prompt caching.", "tags": ["anthropic", "prompt-caching", "performance"], "id": 37} | |
| {"language": "python", "library": "aiohttp", "error_type": "session_per_request", "error_message": "DeprecationWarning: Unclosed client session", "broken_code": "async def fetch(url):\n session = aiohttp.ClientSession()\n resp = await session.get(url)\n return await resp.json()", "explanation": "Creating a new ClientSession per request opens new connections and leaks resources.", "fixed_code": "async def main():\n async with aiohttp.ClientSession() as session:\n resp = await session.get(\"https://api.example.com/data\")\n resp.raise_for_status()\n return await resp.json()", "key_insight": "Create one aiohttp.ClientSession for the app lifetime; use async with to close it properly.", "tags": ["aiohttp", "async", "session", "resource-leak"], "id": 38} | |
| {"language": "python", "library": "httpx", "error_type": "client_not_closed", "error_message": "ResourceWarning: unclosed <AsyncClient>", "broken_code": "client = httpx.AsyncClient()\nresp = await client.get(\"https://api.example.com/data\")", "explanation": "The AsyncClient is never closed, leaking connection resources.", "fixed_code": "async with httpx.AsyncClient() as client:\n resp = await client.get(\"https://api.example.com/data\")\n resp.raise_for_status()", "key_insight": "Always use httpx.AsyncClient as an async context manager to ensure connections are released.", "tags": ["httpx", "resource-leak", "async"], "id": 39} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.stripe.com/v1/charges\")", "explanation": "The stripe API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Token {API_KEY}\"}\nresp = requests.get(\"https://api.stripe.com/v1/charges\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "stripe"], "id": 40} | |
| {"language": "go", "library": "net/http", "error_type": "custom_transport", "error_message": "All connections share the same idle timeout unexpectedly", "broken_code": "client := &http.Client{}", "explanation": "The default Transport uses global settings. For per-client control, create a custom Transport.", "fixed_code": "client := &http.Client{\n Timeout: 30 * time.Second,\n Transport: &http.Transport{\n MaxIdleConns: 100,\n IdleConnTimeout: 90 * time.Second,\n TLSHandshakeTimeout: 10 * time.Second,\n },\n}", "key_insight": "Configure a custom http.Transport per client for fine-grained control over connection pooling and TLS.", "tags": ["go", "http", "transport", "performance"], "id": 41} | |
| {"language": "javascript", "library": "axios", "error_type": "transformResponse", "error_message": "Response data not parsed as expected type", "broken_code": "const resp = await axios.get(\"https://api.example.com/count\");\nconsole.log(typeof resp.data); // \"string\" not \"number\"", "explanation": "axios parses JSON by default but may fail for unusual content types. Use transformResponse.", "fixed_code": "const resp = await axios.get(\"https://api.example.com/count\", {\n transformResponse: [(data) => parseInt(data, 10)]\n});\nconsole.log(typeof resp.data); // \"number\"", "key_insight": "Use transformResponse to post-process the raw response string into the desired type.", "tags": ["axios", "transformResponse", "types"], "id": 42} | |
| {"language": "rest", "library": "generic", "error_type": "http_verbs_misuse", "error_message": "State change via GET causes side effects on caching/replay", "broken_code": "GET /api/users/42/delete\n# Logs out user when link is prefetched by browser", "explanation": "GET must be safe and idempotent; side effects via GET break caching, prefetch, and crawlers.", "fixed_code": "DELETE /api/users/42\n# Or: POST /api/users/42/deactivate", "key_insight": "Use DELETE/POST/PUT for state-changing operations; GET must be safe and idempotent.", "tags": ["rest", "http-verbs", "semantics"], "id": 43} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\")", "explanation": "No timeout set on call to openai-rest endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\", timeout=5)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "openai-rest"], "id": 44} | |
| {"language": "go", "library": "net/http", "error_type": "no_context_timeout", "error_message": "http.Get blocks forever on slow server", "broken_code": "resp, err := http.Get(\"https://slow-api.example.com/data\")", "explanation": "The default http.Get has no timeout. Use a context with deadline.", "fixed_code": "ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\ndefer cancel()\nreq, _ := http.NewRequestWithContext(ctx, http.MethodGet, \"https://slow-api.example.com/data\", nil)\nresp, err := http.DefaultClient.Do(req)\nif err != nil { log.Fatal(err) }\ndefer resp.Body.Close()", "key_insight": "Use http.NewRequestWithContext with context.WithTimeout; bare http.Get has no deadline.", "tags": ["go", "http", "timeout", "context"], "id": 45} | |
| {"language": "python", "library": "stripe", "error_type": "idempotency_key_retry", "error_message": "Duplicate charge on network retry", "broken_code": "stripe.PaymentIntent.create(amount=1000, currency=\"usd\")", "explanation": "Without an idempotency key a retried request creates a second PaymentIntent.", "fixed_code": "import uuid\nstripe.PaymentIntent.create(\n amount=1000,\n currency=\"usd\",\n idempotency_key=str(uuid.uuid4()),\n)", "key_insight": "Generate a UUID per payment action and reuse it on retries; Stripe deduplicates by this key.", "tags": ["stripe", "idempotency", "payments"], "id": 46} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.sendgrid.com/v3/mail/send\")", "explanation": "No timeout set on call to sendgrid endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.sendgrid.com/v3/mail/send\", timeout=60)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "sendgrid"], "id": 47} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.sendgrid.com/v3/mail/send\")", "explanation": "No timeout set on call to sendgrid endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.sendgrid.com/v3/mail/send\", timeout=10)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "sendgrid"], "id": 48} | |
| {"language": "python", "library": "stripe", "error_type": "webhook_raw_bytes", "error_message": "stripe.error.SignatureVerificationError: No signatures found matching", "broken_code": "payload = request.data\nsig = request.headers[\"Stripe-Signature\"]\nevent = stripe.Webhook.construct_event(payload, sig, \"whsec_...\")", "explanation": "The raw bytes must be passed, not a parsed JSON string.", "fixed_code": "payload = request.get_data(as_text=False) # raw bytes\nsig = request.headers[\"Stripe-Signature\"]\ntry:\n event = stripe.Webhook.construct_event(payload, sig, os.environ[\"STRIPE_WEBHOOK_SECRET\"])\nexcept stripe.error.SignatureVerificationError:\n return \"Invalid signature\", 400", "key_insight": "Stripe webhook validation requires raw request bytes; never pass a decoded/parsed body.", "tags": ["stripe", "webhook", "signature"], "id": 49} | |
| {"language": "python", "library": "boto3", "error_type": "no_credentials", "error_message": "botocore.exceptions.NoCredentialsError: Unable to locate credentials", "broken_code": "import boto3\ns3 = boto3.client(\"s3\")\ns3.list_buckets()", "explanation": "No AWS credentials configured. boto3 searches env vars, ~/.aws/credentials, and IAM roles.", "fixed_code": "import boto3, os\ns3 = boto3.client(\n \"s3\",\n aws_access_key_id=os.environ[\"AWS_ACCESS_KEY_ID\"],\n aws_secret_access_key=os.environ[\"AWS_SECRET_ACCESS_KEY\"],\n region_name=\"us-east-1\",\n)\ns3.list_buckets()", "key_insight": "Provide credentials via environment variables or ~/.aws/credentials; never hard-code them in source.", "tags": ["aws", "credentials", "boto3"], "id": 50} | |
| {"language": "typescript", "library": "react-query", "error_type": "error_boundary", "error_message": "Unhandled error crashes the whole React tree", "broken_code": "const { data } = useQuery([\"posts\"], fetchPosts);\nreturn <PostList posts={data} />;", "explanation": "Query errors are not surfaced; if fetchPosts throws, data is undefined and the component crashes.", "fixed_code": "const { data, isError, error } = useQuery([\"posts\"], fetchPosts);\nif (isError) return <ErrorMessage message={error.message} />;\nreturn <PostList posts={data ?? []} />;", "key_insight": "Always destructure isError and error from useQuery and render an error state; don't assume data is defined.", "tags": ["react-query", "typescript", "error-handling"], "id": 51} | |
| {"language": "python", "library": "redis", "error_type": "new_connection_per_call", "error_message": "redis.exceptions.ConnectionError: max number of clients reached", "broken_code": "def handler(event):\n r = redis.Redis(host=\"localhost\", port=6379)\n r.set(\"key\", \"value\")", "explanation": "Creating a new Redis client per request creates a new connection each time.", "fixed_code": "pool = redis.ConnectionPool(host=\"localhost\", port=6379, max_connections=20)\n\ndef handler(event):\n r = redis.Redis(connection_pool=pool)\n r.set(\"key\", \"value\")", "key_insight": "Create one ConnectionPool at startup and share it across handlers.", "tags": ["redis", "connection-pool", "performance"], "id": 52} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\")", "explanation": "The msgraph API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Token {API_KEY}\"}\nresp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "msgraph"], "id": 53} | |
| {"language": "python", "library": "openai", "error_type": "function_calling_history", "error_message": "openai.BadRequestError: messages does not contain assistant turn after tool_call", "broken_code": "messages = [{\"role\": \"user\", \"content\": \"What is the weather?\"}]\nresp = client.chat.completions.create(model=\"gpt-4o\", messages=messages, tools=tools)\ntool_call = resp.choices[0].message.tool_calls[0]\nresult_msg = {\"role\": \"tool\", \"content\": json.dumps(weather), \"tool_call_id\": tool_call.id}\nresp2 = client.chat.completions.create(model=\"gpt-4o\", messages=[result_msg], tools=tools)", "explanation": "The tool result turn must include the full prior conversation including the assistant tool_calls message.", "fixed_code": "messages = [{\"role\": \"user\", \"content\": \"What is the weather?\"}]\nresp = client.chat.completions.create(model=\"gpt-4o\", messages=messages, tools=tools)\nmessages.append(resp.choices[0].message) # keep assistant turn\ntool_call = resp.choices[0].message.tool_calls[0]\nmessages.append({\"role\": \"tool\", \"content\": json.dumps(weather), \"tool_call_id\": tool_call.id})\nresp2 = client.chat.completions.create(model=\"gpt-4o\", messages=messages, tools=tools)", "key_insight": "Always append the assistant message (with tool_calls) to history before adding the tool result.", "tags": ["openai", "function-calling", "tool-use"], "id": 54} | |
| {"language": "python", "library": "grpc", "error_type": "insecure_channel", "error_message": "grpc._channel._InactiveRpcError: StatusCode.UNAVAILABLE \u2014 TLS required", "broken_code": "channel = grpc.insecure_channel(\"api.example.com:443\")\nstub = MyServiceStub(channel)", "explanation": "The server requires TLS but an insecure channel was used.", "fixed_code": "creds = grpc.ssl_channel_credentials()\nchannel = grpc.secure_channel(\"api.example.com:443\", creds)\nstub = MyServiceStub(channel)", "key_insight": "Use grpc.secure_channel() with ssl_channel_credentials() for TLS-required gRPC endpoints.", "tags": ["grpc", "tls", "ssl"], "id": 55} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\")", "explanation": "No timeout set on call to twilio endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\", timeout=10)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "twilio"], "id": 56} | |
| {"language": "python", "library": "httpx", "error_type": "follow_redirects_off", "error_message": "301 response returned instead of final destination", "broken_code": "import httpx\nresp = httpx.get(\"http://api.example.com/data\")", "explanation": "httpx does not follow redirects by default (unlike requests).", "fixed_code": "import httpx\nresp = httpx.get(\"http://api.example.com/data\", follow_redirects=True)\nresp.raise_for_status()", "key_insight": "httpx requires follow_redirects=True explicitly; requests follows redirects by default.", "tags": ["redirect", "httpx"], "id": 57} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.stripe.com/v1/charges\")", "explanation": "No timeout set on call to stripe endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.stripe.com/v1/charges\", timeout=15)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "stripe"], "id": 58} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\")", "explanation": "The openai-rest API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Token {API_KEY}\"}\nresp = requests.get(\"https://api.openai.com/v1/embeddings\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "openai-rest"], "id": 59} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\")", "explanation": "The twilio API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Token {API_KEY}\"}\nresp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "twilio"], "id": 60} | |
| {"language": "javascript", "library": "fetch", "error_type": "json_body_wrong", "error_message": "415 Unsupported Media Type when POSTing JSON", "broken_code": "const resp = await fetch(\"https://api.example.com/users\", {\n method: \"POST\",\n body: { name: \"alice\" }, // object, not string\n});", "explanation": "The body must be a JSON string and Content-Type must be set explicitly.", "fixed_code": "const resp = await fetch(\"https://api.example.com/users\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ name: \"alice\" }),\n});\nif (!resp.ok) throw new Error(`HTTP ${resp.status}`);\nconst data = await resp.json();", "key_insight": "Stringify the body with JSON.stringify() and set Content-Type: application/json header manually.", "tags": ["fetch", "json", "content-type", "415"], "id": 61} | |
| {"language": "rest", "library": "generic", "error_type": "breaking_versioning", "error_message": "Breaking change: v1 clients crash after API field rename", "broken_code": "GET /api/users -> {\"username\": \"alice\"}\n# Changed to:\nGET /api/users -> {\"login\": \"alice\"} # breaks all clients", "explanation": "Field renaming without versioning breaks all existing clients.", "fixed_code": "GET /api/v1/users -> {\"username\": \"alice\"} # unchanged\nGET /api/v2/users -> {\"login\": \"alice\"} # new version", "key_insight": "Never rename or remove fields without bumping the API version; prefer additive changes.", "tags": ["rest", "versioning", "backward-compat"], "id": 62} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.stripe.com/v1/charges\")", "explanation": "No timeout set on call to stripe endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.stripe.com/v1/charges\", timeout=30)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "stripe"], "id": 63} | |
| {"language": "python", "library": "openai", "error_type": "json_mode", "error_message": "json.JSONDecodeError when parsing model output", "broken_code": "resp = client.chat.completions.create(model=\"gpt-4o\", messages=[{\"role\":\"user\",\"content\":\"Return JSON with name and age\"}])\ndata = json.loads(resp.choices[0].message.content)", "explanation": "Without json mode, the model may include markdown fences or explanatory text around the JSON.", "fixed_code": "resp = client.chat.completions.create(\n model=\"gpt-4o\",\n messages=[{\"role\":\"user\",\"content\":\"Return JSON with name and age\"}],\n response_format={\"type\": \"json_object\"},\n)\ndata = json.loads(resp.choices[0].message.content)", "key_insight": "Use response_format={'type': 'json_object'} to guarantee the model returns valid JSON without extra text.", "tags": ["openai", "json-mode", "structured-output"], "id": 64} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\")", "explanation": "No timeout set on call to mapbox endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\", timeout=10)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "mapbox"], "id": 65} | |
| {"language": "python", "library": "gql", "error_type": "n_plus_one_queries", "error_message": "N+1 queries: fetching list then querying each item individually", "broken_code": "users = client.execute(gql(\"query { users { id } }\"))\nfor u in users[\"users\"]:\n detail = client.execute(gql(f'query {{ user(id: {u[\"id\"]}) {{ name email }} }}'))", "explanation": "One query per user makes N+1 round trips. Request nested fields in one query instead.", "fixed_code": "result = client.execute(gql(\"query { users { id name email } }\"))\nfor user in result[\"users\"]:\n process(user)", "key_insight": "Fetch nested fields in a single GraphQL query; avoid N+1 query patterns.", "tags": ["graphql", "n-plus-one", "performance"], "id": 66} | |
| {"language": "go", "library": "net/http", "error_type": "post_no_content_type", "error_message": "415 Unsupported Media Type on POST", "broken_code": "body := strings.NewReader(`{\"name\":\"alice\"}`)\nresp, err := http.Post(\"https://api.example.com/users\", \"\", body)", "explanation": "The Content-Type argument is empty. The API expects application/json.", "fixed_code": "body := strings.NewReader(`{\"name\":\"alice\"}`)\nresp, err := http.Post(\"https://api.example.com/users\", \"application/json\", body)\nif err != nil { log.Fatal(err) }\ndefer resp.Body.Close()", "key_insight": "Always pass \"application/json\" as the content-type argument to http.Post.", "tags": ["go", "http", "json", "content-type"], "id": 67} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.slack.com/api/chat.postMessage\")", "explanation": "The slack API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Bearer {TOKEN}\"}\nresp = requests.get(\"https://api.slack.com/api/chat.postMessage\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "slack"], "id": 68} | |
| {"language": "python", "library": "requests", "error_type": "pagination_keyerror", "error_message": "KeyError: 'next'", "broken_code": "url = \"https://api.example.com/items\"\nwhile True:\n resp = requests.get(url).json()\n process(resp[\"items\"])\n url = resp[\"next\"] # KeyError on last page", "explanation": "The last page has no 'next' key but the code accesses it unconditionally.", "fixed_code": "url = \"https://api.example.com/items\"\nwhile url:\n resp = requests.get(url).json()\n process(resp[\"items\"])\n url = resp.get(\"next\") # None on last page -> loop ends", "key_insight": "Use .get('next') which returns None when the key is absent, terminating the loop cleanly.", "tags": ["pagination", "KeyError"], "id": 69} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\")", "explanation": "No timeout set on call to msgraph endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\", timeout=15)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "msgraph"], "id": 70} | |
| {"language": "javascript", "library": "fetch", "error_type": "no_error_check", "error_message": "Silently receives 4xx/5xx without throwing", "broken_code": "const resp = await fetch(\"https://graph.microsoft.com/v1.0/me/messages\");\nconst data = await resp.json();", "explanation": "fetch() resolves even on HTTP errors from msgraph. Status must be checked manually.", "fixed_code": "const resp = await fetch(\"https://graph.microsoft.com/v1.0/me/messages\");\nif (!resp.ok) throw new Error(`HTTP ${resp.status} from msgraph`);\nconst data = await resp.json();", "key_insight": "fetch() only rejects on network failure; always check resp.ok for HTTP-level errors.", "tags": ["fetch", "error-handling", "msgraph"], "id": 71} | |
| {"language": "javascript", "library": "axios", "error_type": "token_refresh_interceptor", "error_message": "401 after token expiry \u2014 user sees error instead of auto-refresh", "broken_code": "const resp = await api.get(\"/protected\");", "explanation": "The token expired mid-session. An axios response interceptor can refresh it transparently.", "fixed_code": "api.interceptors.response.use(\n res => res,\n async err => {\n if (err.response?.status === 401 && !err.config._retry) {\n err.config._retry = true;\n const token = await refreshAccessToken();\n api.defaults.headers.common[\"Authorization\"] = `Bearer ${token}`;\n return api(err.config);\n }\n return Promise.reject(err);\n }\n);", "key_insight": "Axios response interceptors can catch 401, refresh the token, and replay the original request.", "tags": ["axios", "interceptor", "auth", "refresh-token"], "id": 72} | |
| {"language": "python", "library": "requests", "error_type": "json_body", "error_message": "415 Unsupported Media Type", "broken_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://api.sendgrid.com/v3/mail/send\", data=payload)", "explanation": "data= sends form-encoded body to sendgrid. Use json= for JSON requests.", "fixed_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://api.sendgrid.com/v3/mail/send\", json=payload)\nresp.raise_for_status()", "key_insight": "Use json= not data= to send JSON; requests sets Content-Type automatically.", "tags": ["json", "content-type", "415", "sendgrid"], "id": 73} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\")", "explanation": "The openai-rest API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Bearer {TOKEN}\"}\nresp = requests.get(\"https://api.openai.com/v1/embeddings\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "openai-rest"], "id": 74} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\")", "explanation": "No timeout set on call to openai-rest endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\", timeout=15)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "openai-rest"], "id": 75} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\")", "explanation": "No timeout set on call to msgraph endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\", timeout=5)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "msgraph"], "id": 76} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\")", "explanation": "The mapbox API requires authentication via X-API-Key header.", "fixed_code": "headers = {\"X-API-Key\": \"X-API-Key: {API_KEY}\"}\nresp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in X-API-Key header; requests does not add them automatically.", "tags": ["auth", "401", "mapbox"], "id": 77} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.stripe.com/v1/charges\")", "explanation": "No timeout set on call to stripe endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.stripe.com/v1/charges\", timeout=5)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "stripe"], "id": 78} | |
| {"language": "python", "library": "anthropic", "error_type": "streaming_await_error", "error_message": "TypeError: object Message cannot be used in await expression", "broken_code": "async with client.messages.stream(model=\"claude-opus-4-7\", max_tokens=512, messages=msgs) as stream:\n resp = await stream # wrong", "explanation": "The stream context manager yields an event stream; you iterate it, not await the whole object.", "fixed_code": "async with client.messages.stream(\n model=\"claude-opus-4-7\",\n max_tokens=512,\n messages=[{\"role\": \"user\", \"content\": \"Tell me a story.\"}],\n) as stream:\n async for text in stream.text_stream:\n print(text, end=\"\", flush=True)", "key_insight": "Use async for text in stream.text_stream to consume streaming tokens; do not await the stream itself.", "tags": ["anthropic", "streaming", "async"], "id": 79} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.sendgrid.com/v3/mail/send\")", "explanation": "No timeout set on call to sendgrid endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.sendgrid.com/v3/mail/send\", timeout=15)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "sendgrid"], "id": 80} | |
| {"language": "python", "library": "boto3", "error_type": "dynamodb_decimal", "error_message": "TypeError: Float types are not supported. Use Decimal types instead.", "broken_code": "table.put_item(Item={\"id\": \"1\", \"score\": 9.5})", "explanation": "DynamoDB does not accept Python float; use Decimal from the decimal module.", "fixed_code": "from decimal import Decimal\ntable.put_item(Item={\"id\": \"1\", \"score\": Decimal(\"9.5\")})", "key_insight": "DynamoDB requires Decimal (not float) for numeric values; convert floats with Decimal(str(value)).", "tags": ["aws", "dynamodb", "decimal", "types"], "id": 81} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\")", "explanation": "No timeout set on call to mapbox endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\", timeout=30)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "mapbox"], "id": 82} | |
| {"language": "python", "library": "requests", "error_type": "multipart_upload", "error_message": "400 Bad Request: expected multipart/form-data", "broken_code": "with open(\"image.png\", \"rb\") as f:\n resp = requests.post(\"https://api.example.com/upload\", data=f)", "explanation": "Sending raw bytes via data= doesn't set multipart boundaries. Use files= for multipart upload.", "fixed_code": "with open(\"image.png\", \"rb\") as f:\n resp = requests.post(\"https://api.example.com/upload\", files={\"file\": (\"image.png\", f, \"image/png\")})\nresp.raise_for_status()", "key_insight": "Use files={} for multipart/form-data uploads; it sets the correct Content-Type with boundary automatically.", "tags": ["multipart", "upload", "requests"], "id": 83} | |
| {"language": "typescript", "library": "react-query", "error_type": "mutation_invalidation", "error_message": "Stale data shown after successful mutation", "broken_code": "const mutation = useMutation(updateUser);\nmutation.mutate(payload); // cache not refreshed", "explanation": "After a mutation, query cache must be invalidated to trigger a refetch.", "fixed_code": "const queryClient = useQueryClient();\nconst mutation = useMutation(updateUser, {\n onSuccess: () => {\n queryClient.invalidateQueries([\"user\"]);\n },\n});\nmutation.mutate(payload);", "key_insight": "Use onSuccess + queryClient.invalidateQueries() to refresh stale data after mutations.", "tags": ["react-query", "typescript", "mutation", "invalidation"], "id": 84} | |
| {"language": "javascript", "library": "fetch", "error_type": "cors_blocked", "error_message": "Access blocked by CORS policy", "broken_code": "const resp = await fetch(\"https://api.example.com/data\");\nconst data = await resp.json();", "explanation": "CORS is enforced by the browser. The fix is server-side or proxy via your backend.", "fixed_code": "// Proxy through your backend:\nconst resp = await fetch(\"/api/proxy/data\");\nconst data = await resp.json();", "key_insight": "CORS cannot be fixed client-side; configure the target server or proxy via your own backend.", "tags": ["cors", "browser", "fetch"], "id": 85} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\")", "explanation": "No timeout set on call to github endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\", timeout=10)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "github"], "id": 86} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\")", "explanation": "The mapbox API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Token {API_KEY}\"}\nresp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "mapbox"], "id": 87} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\")", "explanation": "The github API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Token {API_KEY}\"}\nresp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "github"], "id": 88} | |
| {"language": "typescript", "library": "openai", "error_type": "structured_output", "error_message": "json.JSONDecodeError: model returned prose instead of JSON", "broken_code": "const resp = await client.chat.completions.create({\n model: \"gpt-4o\", messages: [{role:\"user\", content:\"Extract: \" + text}]\n});\nconst data = JSON.parse(resp.choices[0].message.content!);", "explanation": "Without JSON mode or structured output, the model may include markdown or prose.", "fixed_code": "import { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod\";\n\nconst schema = z.object({ name: z.string(), age: z.number() });\nconst resp = await client.beta.chat.completions.parse({\n model: \"gpt-4o\",\n messages: [{ role: \"user\", content: \"Extract: \" + text }],\n response_format: zodResponseFormat(schema, \"person\"),\n});\nconst data = resp.choices[0].message.parsed;", "key_insight": "Use zodResponseFormat with client.beta.chat.completions.parse() for type-safe structured output.", "tags": ["typescript", "openai", "structured-output", "zod"], "id": 89} | |
| {"language": "python", "library": "boto3", "error_type": "waiter_usage", "error_message": "Checking EC2 instance state in a polling loop manually", "broken_code": "import time\nec2.start_instances(InstanceIds=[instance_id])\nwhile True:\n state = ec2.describe_instances(InstanceIds=[instance_id])[\"Reservations\"][0][\"Instances\"][0][\"State\"][\"Name\"]\n if state == \"running\":\n break\n time.sleep(5)", "explanation": "Manual polling is fragile. boto3 provides built-in waiters for common state transitions.", "fixed_code": "ec2.start_instances(InstanceIds=[instance_id])\nwaiter = ec2.get_waiter(\"instance_running\")\nwaiter.wait(InstanceIds=[instance_id])", "key_insight": "Use boto3 waiters instead of manual polling loops; they handle retries and timeouts correctly.", "tags": ["aws", "ec2", "waiter"], "id": 90} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\")", "explanation": "The twilio API requires authentication via X-API-Key header.", "fixed_code": "headers = {\"X-API-Key\": \"X-API-Key: {API_KEY}\"}\nresp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in X-API-Key header; requests does not add them automatically.", "tags": ["auth", "401", "twilio"], "id": 91} | |
| {"language": "typescript", "library": "react-query", "error_type": "stale_time_missing", "error_message": "Excessive refetches on every component mount", "broken_code": "const { data } = useQuery([\"user\", id], () => fetchUser(id));", "explanation": "Without staleTime, react-query refetches on every mount and window focus.", "fixed_code": "const { data } = useQuery(\n [\"user\", id],\n () => fetchUser(id),\n { staleTime: 5 * 60 * 1000 } // 5 minutes\n);", "key_insight": "Set staleTime to match the data freshness requirement; default 0 causes aggressive refetching.", "tags": ["react-query", "typescript", "stale-time", "performance"], "id": 92} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.sendgrid.com/v3/mail/send\")", "explanation": "No timeout set on call to sendgrid endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.sendgrid.com/v3/mail/send\", timeout=30)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "sendgrid"], "id": 93} | |
| {"language": "python", "library": "requests", "error_type": "json_body", "error_message": "415 Unsupported Media Type", "broken_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://api.stripe.com/v1/charges\", data=payload)", "explanation": "data= sends form-encoded body to stripe. Use json= for JSON requests.", "fixed_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://api.stripe.com/v1/charges\", json=payload)\nresp.raise_for_status()", "key_insight": "Use json= not data= to send JSON; requests sets Content-Type automatically.", "tags": ["json", "content-type", "415", "stripe"], "id": 94} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.sendgrid.com/v3/mail/send\")", "explanation": "The sendgrid API requires authentication via Authorization header.", "fixed_code": "headers = {\"Authorization\": \"Bearer {TOKEN}\"}\nresp = requests.get(\"https://api.sendgrid.com/v3/mail/send\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in Authorization header; requests does not add them automatically.", "tags": ["auth", "401", "sendgrid"], "id": 95} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\")", "explanation": "The github API requires authentication via X-API-Key header.", "fixed_code": "headers = {\"X-API-Key\": \"X-API-Key: {API_KEY}\"}\nresp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in X-API-Key header; requests does not add them automatically.", "tags": ["auth", "401", "github"], "id": 96} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\")", "explanation": "No timeout set on call to openai-rest endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\", timeout=10)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "openai-rest"], "id": 97} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\")", "explanation": "No timeout set on call to twilio endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\", timeout=60)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "twilio"], "id": 98} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\")", "explanation": "No timeout set on call to twilio endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\", timeout=15)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "twilio"], "id": 99} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\")", "explanation": "No timeout set on call to msgraph endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\", timeout=60)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "msgraph"], "id": 100} | |
| {"language": "python", "library": "anthropic", "error_type": "max_tokens_required", "error_message": "anthropic.BadRequestError: max_tokens is required", "broken_code": "resp = client.messages.create(model=\"claude-opus-4-7\", messages=[{\"role\":\"user\",\"content\":\"Hello\"}])", "explanation": "max_tokens is a required parameter for the Anthropic Messages API.", "fixed_code": "resp = client.messages.create(\n model=\"claude-opus-4-7\",\n max_tokens=1024,\n messages=[{\"role\": \"user\", \"content\": \"Hello\"}],\n)\nprint(resp.content[0].text)", "key_insight": "The Anthropic API always requires max_tokens; there is no default \u2014 set it explicitly.", "tags": ["anthropic", "max_tokens", "required"], "id": 101} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\")", "explanation": "No timeout set on call to github endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\", timeout=5)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "github"], "id": 102} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\")", "explanation": "No timeout set on call to mapbox endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.mapbox.com/geocoding/v5/mapbox.places/\", timeout=5)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "mapbox"], "id": 103} | |
| {"language": "javascript", "library": "fetch", "error_type": "no_error_check", "error_message": "Silently receives 4xx/5xx without throwing", "broken_code": "const resp = await fetch(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\");\nconst data = await resp.json();", "explanation": "fetch() resolves even on HTTP errors from twilio. Status must be checked manually.", "fixed_code": "const resp = await fetch(\"https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages\");\nif (!resp.ok) throw new Error(`HTTP ${resp.status} from twilio`);\nconst data = await resp.json();", "key_insight": "fetch() only rejects on network failure; always check resp.ok for HTTP-level errors.", "tags": ["fetch", "error-handling", "twilio"], "id": 104} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.stripe.com/v1/charges\")", "explanation": "No timeout set on call to stripe endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.stripe.com/v1/charges\", timeout=10)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "stripe"], "id": 105} | |
| {"language": "python", "library": "openai", "error_type": "streaming_type_error", "error_message": "TypeError: ChatCompletion object is not iterable", "broken_code": "resp = client.chat.completions.create(model=\"gpt-4o\", messages=msgs, stream=True)\nprint(resp.choices[0].message.content)", "explanation": "With stream=True the response is a generator, not a ChatCompletion object.", "fixed_code": "resp = client.chat.completions.create(model=\"gpt-4o\", messages=msgs, stream=True)\nfor chunk in resp:\n delta = chunk.choices[0].delta.content or \"\"\n print(delta, end=\"\", flush=True)", "key_insight": "With stream=True, iterate over the response chunks; .choices[0].delta.content carries each token.", "tags": ["openai", "streaming"], "id": 106} | |
| {"language": "python", "library": "gql", "error_type": "no_variables", "error_message": "GraphQLError: Variable id of required type ID! was not provided.", "broken_code": "from gql import gql, Client\nquery = gql(\"query { user(id: 1) { name } }\")", "explanation": "Hard-coding IDs in the query string means variables were declared but not bound.", "fixed_code": "query = gql(\"query GetUser($id: ID!) { user(id: $id) { name email } }\")\nresult = client.execute(query, variable_values={\"id\": \"1\"})", "key_insight": "Declare query variables with $name: Type! and pass them via variable_values={}.", "tags": ["graphql", "variables"], "id": 107} | |
| {"language": "typescript", "library": "openai", "error_type": "stream_type_mismatch", "error_message": "Type error: AsyncIterable not assignable to ChatCompletion", "broken_code": "const resp: ChatCompletion = await client.chat.completions.create({\n model: \"gpt-4o\", messages, stream: true,\n});", "explanation": "With stream: true the return type is Stream<ChatCompletionChunk>, not ChatCompletion.", "fixed_code": "const stream = client.chat.completions.stream({ model: \"gpt-4o\", messages });\nfor await (const chunk of stream) {\n const delta = chunk.choices[0]?.delta?.content ?? \"\";\n process.stdout.write(delta);\n}\nconst final = await stream.finalChatCompletion();", "key_insight": "Use the .stream() helper for typed streaming; avoid .create({ stream: true }) in TypeScript.", "tags": ["typescript", "openai", "streaming", "types"], "id": 108} | |
| {"language": "python", "library": "grpc", "error_type": "deadline_missing", "error_message": "gRPC call hangs indefinitely on server failure", "broken_code": "stub = MyServiceStub(channel)\nresp = stub.GetData(request)", "explanation": "Without a deadline/timeout, a gRPC call can block forever if the server hangs.", "fixed_code": "import grpc\nstub = MyServiceStub(channel)\ntry:\n resp = stub.GetData(request, timeout=10) # seconds\nexcept grpc.RpcError as e:\n if e.code() == grpc.StatusCode.DEADLINE_EXCEEDED:\n print(\"RPC timed out\")", "key_insight": "Always pass timeout= to gRPC stub calls; handle DEADLINE_EXCEEDED to fail fast.", "tags": ["grpc", "timeout", "deadline"], "id": 109} | |
| {"language": "python", "library": "grpc", "error_type": "metadata_auth", "error_message": "grpc.StatusCode.UNAUTHENTICATED: missing token", "broken_code": "stub = MyServiceStub(channel)\nresp = stub.GetData(request)", "explanation": "gRPC metadata (equivalent of HTTP headers) must carry the auth token.", "fixed_code": "metadata = [(\"authorization\", f\"Bearer {token}\")]\nresp = stub.GetData(request, metadata=metadata)", "key_insight": "Pass auth tokens via gRPC metadata tuples, not request body; metadata is the gRPC equivalent of HTTP headers.", "tags": ["grpc", "auth", "metadata"], "id": 110} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.slack.com/api/chat.postMessage\")", "explanation": "No timeout set on call to slack endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.slack.com/api/chat.postMessage\", timeout=15)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "slack"], "id": 111} | |
| {"language": "javascript", "library": "fetch", "error_type": "memory_leak_unmount", "error_message": "Cannot update state on unmounted component (React warning)", "broken_code": "useEffect(() => {\n fetch(\"/api/data\").then(r => r.json()).then(setData);\n}, []);", "explanation": "The fetch continues after unmount, then sets state on an unmounted component.", "fixed_code": "useEffect(() => {\n const controller = new AbortController();\n fetch(\"/api/data\", { signal: controller.signal })\n .then(r => r.json())\n .then(setData)\n .catch(err => { if (err.name !== \"AbortError\") console.error(err); });\n return () => controller.abort();\n}, []);", "key_insight": "Use AbortController to cancel in-flight fetches on component unmount; ignore AbortError.", "tags": ["fetch", "abort", "react", "memory-leak"], "id": 112} | |
| {"language": "python", "library": "requests", "error_type": "json_body", "error_message": "415 Unsupported Media Type", "broken_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://api.slack.com/api/chat.postMessage\", data=payload)", "explanation": "data= sends form-encoded body to slack. Use json= for JSON requests.", "fixed_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://api.slack.com/api/chat.postMessage\", json=payload)\nresp.raise_for_status()", "key_insight": "Use json= not data= to send JSON; requests sets Content-Type automatically.", "tags": ["json", "content-type", "415", "slack"], "id": 113} | |
| {"language": "python", "library": "requests", "error_type": "proxy_config", "error_message": "requests.exceptions.ProxyError: unable to connect to proxy", "broken_code": "resp = requests.get(\"https://api.example.com/data\", proxies={\"http\": \"http://proxy:8080\"})", "explanation": "HTTPS traffic needs the https key in proxies dict, not just http.", "fixed_code": "proxies = {\"http\": \"http://proxy:8080\", \"https\": \"http://proxy:8080\"}\nresp = requests.get(\"https://api.example.com/data\", proxies=proxies)\nresp.raise_for_status()", "key_insight": "Specify both 'http' and 'https' keys in proxies dict; HTTPS URLs use the 'https' entry.", "tags": ["proxy", "https", "requests"], "id": 114} | |
| {"language": "go", "library": "net/http", "error_type": "body_not_closed", "error_message": "Resource leak: response body not closed", "broken_code": "resp, err := http.Get(\"https://api.example.com/data\")\nif err != nil { log.Fatal(err) }\nbody, _ := io.ReadAll(resp.Body)", "explanation": "The response body must be closed to release the underlying TCP connection.", "fixed_code": "resp, err := http.Get(\"https://api.example.com/data\")\nif err != nil { log.Fatal(err) }\ndefer resp.Body.Close()\nbody, err := io.ReadAll(resp.Body)\nif err != nil { log.Fatal(err) }", "key_insight": "Always defer resp.Body.Close() immediately after checking the error.", "tags": ["go", "http", "resource-leak"], "id": 115} | |
| {"language": "python", "library": "httpx", "error_type": "timeout_tuple", "error_message": "httpx.TimeoutException on slow endpoint", "broken_code": "import httpx\nclient = httpx.Client()\nresp = client.get(\"https://slow.example.com/api\")", "explanation": "Default timeout may be too short or too long; httpx.Client defaults to 5s total timeout.", "fixed_code": "import httpx\nclient = httpx.Client(timeout=httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0))\nresp = client.get(\"https://slow.example.com/api\")\nresp.raise_for_status()", "key_insight": "Use httpx.Timeout with separate connect/read/write timeouts for fine-grained control.", "tags": ["timeout", "httpx"], "id": 116} | |
| {"language": "python", "library": "google-auth", "error_type": "expired_token", "error_message": "google.auth.exceptions.TransportError: 401 Unauthorized on long-running job", "broken_code": "creds = service_account.Credentials.from_service_account_file(\"key.json\", scopes=SCOPES)\n# ... long job ...\nservice.spreadsheets().values().get(...).execute() # token expired", "explanation": "OAuth tokens expire after ~1 hour. Use AuthorizedSession to refresh automatically.", "fixed_code": "from google.auth.transport.requests import AuthorizedSession\ncreds = service_account.Credentials.from_service_account_file(\"key.json\", scopes=SCOPES)\nauthed_session = AuthorizedSession(creds)\nresp = authed_session.get(\"https://sheets.googleapis.com/v4/spreadsheets/...\")", "key_insight": "Use AuthorizedSession instead of bare requests; it handles token refresh transparently.", "tags": ["google", "auth", "token-refresh"], "id": 117} | |
| {"language": "rest", "library": "generic", "error_type": "idempotency_key", "error_message": "Duplicate charges created when POST retried on timeout", "broken_code": "POST /payments\n{ \"amount\": 100, \"currency\": \"USD\" }", "explanation": "POST is not idempotent. A network retry creates a duplicate payment.", "fixed_code": "POST /payments\nIdempotency-Key: a8098c1a-f86e-11da-bd1a-00112444be1e\n{ \"amount\": 100, \"currency\": \"USD\" }", "key_insight": "Generate a UUID idempotency key per payment intent and retry safely; server deduplicates.", "tags": ["rest", "idempotency", "payments", "retry"], "id": 118} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.stripe.com/v1/charges\")", "explanation": "No timeout set on call to stripe endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.stripe.com/v1/charges\", timeout=60)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "stripe"], "id": 119} | |
| {"language": "python", "library": "requests", "error_type": "rate_limit_429", "error_message": "429 Too Many Requests", "broken_code": "for item_id in item_ids:\n resp = requests.get(f\"https://api.example.com/items/{item_id}\")\n results.append(resp.json())", "explanation": "Hammering the API in a tight loop hits the rate limit. The server returns 429.", "fixed_code": "import time\nfor item_id in item_ids:\n resp = requests.get(f\"https://api.example.com/items/{item_id}\")\n if resp.status_code == 429:\n time.sleep(int(resp.headers.get(\"Retry-After\", 5)))\n resp = requests.get(f\"https://api.example.com/items/{item_id}\")\n resp.raise_for_status()\n results.append(resp.json())", "key_insight": "Respect Retry-After header on 429; add delays between rapid sequential requests.", "tags": ["rate-limit", "429", "retry"], "id": 120} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\")", "explanation": "No timeout set on call to openai-rest endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\", timeout=60)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "openai-rest"], "id": 121} | |
| {"language": "python", "library": "anthropic", "error_type": "tool_result_format", "error_message": "anthropic.BadRequestError: tool_result must follow tool_use block", "broken_code": "messages = [{\"role\": \"user\", \"content\": \"Check inventory for product 42\"}]\nresp = client.messages.create(model=\"claude-opus-4-7\", max_tokens=512, tools=tools, messages=messages)\ntool_id = resp.content[0].id\nmessages.append({\"role\": \"user\", \"content\": [{\"type\": \"tool_result\", \"tool_use_id\": tool_id, \"content\": \"42 units\"}]})", "explanation": "Tool results must be in a user turn after an assistant turn that contains the matching tool_use block.", "fixed_code": "messages.append({\"role\": \"assistant\", \"content\": resp.content}) # include full assistant response\nmessages.append({\"role\": \"user\", \"content\": [{\"type\": \"tool_result\", \"tool_use_id\": tool_id, \"content\": \"42 units\"}]})\nresp2 = client.messages.create(model=\"claude-opus-4-7\", max_tokens=512, tools=tools, messages=messages)", "key_insight": "Append the full assistant message (with tool_use blocks) before submitting the tool_result user turn.", "tags": ["anthropic", "tool-use", "messages"], "id": 122} | |
| {"language": "python", "library": "aiohttp", "error_type": "timeout_config", "error_message": "aiohttp.ServerTimeoutError on slow endpoint", "broken_code": "async with aiohttp.ClientSession() as session:\n resp = await session.get(\"https://slow.example.com/api\")", "explanation": "No timeout configured; slow servers block indefinitely.", "fixed_code": "timeout = aiohttp.ClientTimeout(total=30, connect=5)\nasync with aiohttp.ClientSession(timeout=timeout) as session:\n resp = await session.get(\"https://slow.example.com/api\")\n resp.raise_for_status()", "key_insight": "Set aiohttp.ClientTimeout with total and connect limits to avoid hanging on slow servers.", "tags": ["aiohttp", "timeout", "async"], "id": 123} | |
| {"language": "javascript", "library": "axios", "error_type": "concurrent_requests", "error_message": "Sequential requests when they could run in parallel", "broken_code": "const users = await axios.get(\"/users\");\nconst posts = await axios.get(\"/posts\");\n// takes 2x as long", "explanation": "Sequential awaits are unnecessarily slow when the requests are independent.", "fixed_code": "const [usersResp, postsResp] = await Promise.all([\n axios.get(\"/users\"),\n axios.get(\"/posts\"),\n]);\nconst users = usersResp.data;\nconst posts = postsResp.data;", "key_insight": "Use Promise.all() to fire independent requests in parallel and wait for all results at once.", "tags": ["axios", "performance", "parallel", "promise-all"], "id": 124} | |
| {"language": "python", "library": "requests", "error_type": "auth_missing", "error_message": "401 Unauthorized", "broken_code": "resp = requests.get(\"https://api.openai.com/v1/embeddings\")", "explanation": "The openai-rest API requires authentication via X-API-Key header.", "fixed_code": "headers = {\"X-API-Key\": \"X-API-Key: {API_KEY}\"}\nresp = requests.get(\"https://api.openai.com/v1/embeddings\", headers=headers)\nresp.raise_for_status()", "key_insight": "Attach credentials in X-API-Key header; requests does not add them automatically.", "tags": ["auth", "401", "openai-rest"], "id": 125} | |
| {"language": "typescript", "library": "openai", "error_type": "tool_vs_text_narrowing", "error_message": "TypeError: Cannot read property text of undefined (tool call vs text response)", "broken_code": "const resp = await client.chat.completions.create({ model: \"gpt-4o\", messages });\nconst text = resp.choices[0].message.content; // null when tool was called", "explanation": "When the model calls a tool, message.content is null and message.tool_calls is populated.", "fixed_code": "const choice = resp.choices[0].message;\nif (choice.tool_calls && choice.tool_calls.length > 0) {\n const call = choice.tool_calls[0];\n const args = JSON.parse(call.function.arguments);\n // handle tool call\n} else {\n const text = choice.content ?? \"\";\n // handle text response\n}", "key_insight": "Always check message.tool_calls before message.content; they are mutually exclusive.", "tags": ["typescript", "openai", "tool-calls", "type-narrowing"], "id": 126} | |
| {"language": "python", "library": "httpx", "error_type": "async_client_no_await", "error_message": "RuntimeError: no running event loop", "broken_code": "import httpx\nresp = httpx.AsyncClient().get(\"https://api.example.com/data\")", "explanation": "AsyncClient.get() is a coroutine; it must be awaited inside an async function.", "fixed_code": "import httpx, asyncio\n\nasync def fetch():\n async with httpx.AsyncClient() as client:\n resp = await client.get(\"https://api.example.com/data\")\n resp.raise_for_status()\n return resp.json()\n\ndata = asyncio.run(fetch())", "key_insight": "httpx async methods are coroutines \u2014 always await them inside async def and use async with for the client.", "tags": ["async", "httpx", "event-loop"], "id": 127} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\")", "explanation": "No timeout set on call to msgraph endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://graph.microsoft.com/v1.0/me/messages\", timeout=30)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "msgraph"], "id": 128} | |
| {"language": "javascript", "library": "fetch", "error_type": "no_error_check", "error_message": "Silently receives 4xx/5xx without throwing", "broken_code": "const resp = await fetch(\"https://api.stripe.com/v1/charges\");\nconst data = await resp.json();", "explanation": "fetch() resolves even on HTTP errors from stripe. Status must be checked manually.", "fixed_code": "const resp = await fetch(\"https://api.stripe.com/v1/charges\");\nif (!resp.ok) throw new Error(`HTTP ${resp.status} from stripe`);\nconst data = await resp.json();", "key_insight": "fetch() only rejects on network failure; always check resp.ok for HTTP-level errors.", "tags": ["fetch", "error-handling", "stripe"], "id": 129} | |
| {"language": "python", "library": "requests", "error_type": "json_body", "error_message": "415 Unsupported Media Type", "broken_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://api.github.com/repos/{owner}/{repo}/issues\", data=payload)", "explanation": "data= sends form-encoded body to github. Use json= for JSON requests.", "fixed_code": "payload = {\"key\": \"value\"}\nresp = requests.post(\"https://api.github.com/repos/{owner}/{repo}/issues\", json=payload)\nresp.raise_for_status()", "key_insight": "Use json= not data= to send JSON; requests sets Content-Type automatically.", "tags": ["json", "content-type", "415", "github"], "id": 130} | |
| {"language": "python", "library": "requests", "error_type": "timeout_missing", "error_message": "requests.exceptions.ReadTimeout: HTTPSConnectionPool: Read timed out.", "broken_code": "resp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\")", "explanation": "No timeout set on call to github endpoint. Slow or down servers block indefinitely.", "fixed_code": "resp = requests.get(\"https://api.github.com/repos/{owner}/{repo}/issues\", timeout=15)\nresp.raise_for_status()", "key_insight": "Always set a timeout on requests to external APIs; the default is None (wait forever).", "tags": ["timeout", "requests", "github"], "id": 131} | |
| {"language": "javascript", "library": "fetch", "error_type": "no_error_check", "error_message": "Silently receives 4xx/5xx without throwing", "broken_code": "const resp = await fetch(\"https://api.github.com/repos/{owner}/{repo}/issues\");\nconst data = await resp.json();", "explanation": "fetch() resolves even on HTTP errors from github. Status must be checked manually.", "fixed_code": "const resp = await fetch(\"https://api.github.com/repos/{owner}/{repo}/issues\");\nif (!resp.ok) throw new Error(`HTTP ${resp.status} from github`);\nconst data = await resp.json();", "key_insight": "fetch() only rejects on network failure; always check resp.ok for HTTP-level errors.", "tags": ["fetch", "error-handling", "github"], "id": 132} | |