{"record":{"id":"236589b25bdf0c70","repo":"karatelabs/karate","slug":"failed-to-write-file","errorCode":null,"errorMessage":"Failed to write file: ","messagePattern":"Failed to write file: ","errorType":"exception","errorClass":"RuntimeException","httpStatus":null,"severity":"error","filePath":"karate-core/src/main/java/io/karatelabs/core/KarateJs.java","lineNumber":1171,"sourceCode":"            // Create the full path\n            File file = new File(outputDir, path);\n\n            // Ensure parent directories exist\n            File parent = file.getParentFile();\n            if (parent != null && !parent.exists()) {\n                parent.mkdirs();\n            }\n\n            // Convert value to bytes\n            byte[] bytes = KarateJsUtils.convertToBytes(value);\n\n            // Write to file\n            try {\n                Files.write(file.toPath(), bytes);\n                logger.debug(\"wrote {} bytes to: {}\", bytes.length, file.getAbsolutePath());\n                return file;\n            } catch (Exception e) {\n                throw new RuntimeException(\"Failed to write file: \" + file.getAbsolutePath(), e);\n            }\n        };\n    }\n\n    /**\n     * JS-side access to the active browser driver, initialising it lazily from\n     * {@code configure driver = { ... }} on first read — the JS equivalent of the\n     * {@code * driver ...} step. Useful when driver lifecycle is orchestrated inside\n     * a JS function (e.g. iterating over a list of browser configs in a grid run),\n     * where Gherkin steps aren't reachable per iteration. Returns the same instance\n     * exposed via the {@code driver} root binding; after {@code driver.quit()} a\n     * subsequent read re-inits cleanly via {@link ScenarioRuntime#getDriver()}.\n     */\n    private io.karatelabs.driver.Driver getDriverLazy() {\n        ScenarioRuntime rt = getRuntime();\n        if (rt == null) {\n            throw new RuntimeException(\"karate.driver can only be read within a scenario\");\n        }","sourceCodeStart":1153,"sourceCodeEnd":1189,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-core/src/main/java/io/karatelabs/core/KarateJs.java#L1153-L1189","documentation":"karate.write() wraps java.nio.Files.write in a try/catch; when the actual file write fails for any reason (bad path, permissions, disk full, invalid characters), the exception is rethrown as a RuntimeException naming the absolute target path, with the original cause attached.","triggerScenarios":"Writing to a path containing illegal filename characters (e.g. ':' or '/' derived from a URL), the output directory not existing and not being creatable, no write permission on target/karate-reports, or disk full.","commonSituations":"Deriving the filename from an API response or URL with characters invalid on the OS; CI containers with read-only workspaces; very long paths on Windows; report directory wiped by a concurrent build.","solutions":["Read the chained cause ('Caused by') for the real OS error and fix accordingly","Sanitize the path argument: strip/replace illegal characters and avoid directory separators","Ensure the output directory exists and is writable (check karate.outputDir / target/karate-reports permissions)","Use a simple relative filename so Karate resolves it under the configured output dir."],"exampleFix":"// before\nkarate.write(data, url + '.json'); // url contains ':' and '/'\n// after\nvar name = url.replace(/[^a-zA-Z0-9._-]/g, '_');\nkarate.write(data, name + '.json');","handlingStrategy":"try-catch","validationCode":"// JS\nvar safe = path.replace(/[^a-zA-Z0-9._-]/g, '_');\nkarate.write(value, safe);","typeGuard":"function isSafeFileName(p) { return /^[a-zA-Z0-9._-]+$/.test(p); }","tryCatchPattern":"try { karate.write(value, path); } catch (e) { karate.warn('file write failed: ' + e + ' cause=' + e.cause); }","preventionTips":["Sanitize filenames derived from URLs/API data","Ensure the output directory exists and is writable in CI","Watch the 'Caused by' for the real OS-level reason","Keep paths short (Windows path-length limits)"],"tags":["file-io","ioexception","karate-js"],"backgroundTag":"file-write-failed","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-19T12:17:13.211Z"}