{"id":"b446fa9fd3bcbf8d","repo":"square/okhttp","slug":"unexpected-code-b446fa","errorCode":null,"errorMessage":"Unexpected code ","messagePattern":"Unexpected code ","errorType":"exception","errorClass":"IOException","httpStatus":null,"severity":"error","filePath":"samples/guide/src/main/java/okhttp3/recipes/CacheResponse.java","lineNumber":44,"sourceCode":"  private final OkHttpClient client;\n\n  public CacheResponse(File cacheDirectory) throws Exception {\n    int cacheSize = 10 * 1024 * 1024; // 10 MiB\n    Cache cache = new Cache(cacheDirectory, cacheSize);\n\n    client = new OkHttpClient.Builder()\n        .cache(cache)\n        .build();\n  }\n\n  public void run() throws Exception {\n    Request request = new Request.Builder()\n        .url(\"http://publicobject.com/helloworld.txt\")\n        .build();\n\n    String response1Body;\n    try (Response response1 = client.newCall(request).execute()) {\n      if (!response1.isSuccessful()) throw new IOException(\"Unexpected code \" + response1);\n\n      response1Body = response1.body().string();\n      System.out.println(\"Response 1 response:          \" + response1);\n      System.out.println(\"Response 1 cache response:    \" + response1.cacheResponse());\n      System.out.println(\"Response 1 network response:  \" + response1.networkResponse());\n    }\n\n    String response2Body;\n    try (Response response2 = client.newCall(request).execute()) {\n      if (!response2.isSuccessful()) throw new IOException(\"Unexpected code \" + response2);\n\n      response2Body = response2.body().string();\n      System.out.println(\"Response 2 response:          \" + response2);\n      System.out.println(\"Response 2 cache response:    \" + response2.cacheResponse());\n      System.out.println(\"Response 2 network response:  \" + response2.networkResponse());\n    }\n\n    System.out.println(\"Response 2 equals Response 1? \" + response1Body.equals(response2Body));","sourceCodeStart":26,"sourceCodeEnd":62,"githubUrl":"https://github.com/square/okhttp/blob/4fc083138014aba3d0078f5c26d1ce84815fa984/samples/guide/src/main/java/okhttp3/recipes/CacheResponse.java#L26-L62","documentation":"Recipe-level guard on the FIRST of two identical GETs that demonstrate HTTP caching. The client is built with a 10 MiB disk Cache; on the first request the cache is cold so the response must come from the network. If that network response is not 2xx, java.io.IOException(\"Unexpected code \" + response1) is thrown before the cache is populated.","triggerScenarios":"First client.newCall(request).execute() for http://publicobject.com/helloworld.txt with caching enabled. Fires on any non-2xx from the origin: host down (would actually be transport IOException, not this), 404, 503, or a non-cacheable error. Because this is the cache-warming request, failure here means the second request (error [4]) cannot be a cache hit either.","commonSituations":"Cache directory not writable (separate failure: the cache silently no-ops or throws earlier); origin server returning 5xx; running offline and expecting the cache to serve stale content (OkHttp does not serve stale-on-error unless a separate fallback is configured); the demo domain returning a redirect to https.","solutions":["Check response1.code(), response1.cacheResponse(), and response1.networkResponse() to determine whether it was a network round-trip and what the origin said.","Verify the cache directory exists and is writable; check Cache.directory() and Cache.size() after the call.","Confirm the URL is reachable with curl; the cache only helps once the origin is healthy.","Use https:// to avoid redirect-related status codes."],"exampleFix":"// before\ntry (Response response1 = client.newCall(request).execute()) {\n  if (!response1.isSuccessful()) throw new IOException(\"Unexpected code \" + response1);\n  ...\n}\n\n// after\ntry (Response response1 = client.newCall(request).execute()) {\n  if (!response1.isSuccessful()) {\n    throw new IOException(\"Warm-up failed: HTTP \" + response1.code()\n        + \" network=\" + response1.networkResponse()\n        + \" cache=\" + response1.cacheResponse());\n  }\n  ...\n}","handlingStrategy":"validation","validationCode":"// Verify cache directory is writable before constructing the client\nFile dir = cacheDirectory;\nif (!dir.exists() && !dir.mkdirs()) throw new IOException(\"Cannot create cache dir: \" + dir);\nif (!dir.canWrite()) throw new IOException(\"Cache dir not writable: \" + dir);\nCache cache = new Cache(dir, 10 * 1024 * 1024);\nOkHttpClient client = new OkHttpClient.Builder().cache(cache).build();","typeGuard":null,"tryCatchPattern":"try (Response response1 = client.newCall(request).execute()) {\n  if (!response1.isSuccessful()) {\n    throw new HttpException(response1.code(),\n        \"network=\" + response1.networkResponse() + \", cache=\" + response1.cacheResponse());\n  }\n  // warm the cache\n}","preventionTips":["Ensure the cache directory exists and is writable.","Confirm the origin is reachable before expecting a cache warm-up.","Use https:// to avoid redirect-related status codes.","Log networkResponse() vs cacheResponse() to understand which path served the response."],"tags":["okhttp","http-status","caching","java"],"analyzedSha":"4fc083138014aba3d0078f5c26d1ce84815fa984","analyzedAt":"2026-08-04T19:09:04.639Z","schemaVersion":2}