OpenAPITools/openapi-generator · error · RuntimeException

Could not generate model '{modelName}'

Error message

Could not generate model '{modelName}'

What it means

Thrown from DefaultGenerator.generateModels (the file-writing loop, distinct from the processing loop of error [1]): for each already-processed model it calls generateModel, generateModelTests and generateModelDocumentation, and wraps any failure of those three steps with the model name. At this point the model data was built successfully; the failure is in template selection/rendering or file writing (IOException from processTemplateToFile, missing template file, Mustache engine failure on the model's data).

Source

Thrown at modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java:608

                if (config.typeMapping().containsKey(modelName)) {
                    String mappedTypeName = config.typeMapping().get(modelName);
                    if (config.importMapping().containsKey(mappedTypeName)) {
                        LOGGER.info("Model {} (type-mapped to {}) not generated due to import mapping", modelName, mappedTypeName);
                        continue;
                    }
                }

                // to generate model files
                generateModel(files, models, modelName);

                // to generate model test files
                generateModelTests(files, models, modelName);

                // to generate model documentation files
                generateModelDocumentation(files, models, modelName);

            } catch (Exception e) {
                throw new RuntimeException("Could not generate model '" + modelName + "'", e);
            }
        }
        if (GlobalSettings.getProperty("debugModels") != null) {
            LOGGER.info("############ Model info ############");
            Json.prettyPrint(allModels);
        }
    }

    /**
     * this method guesses the schema type of in parent model used variable and if the schema type is available it let the generate the model for the type of this variable
     */
    private void generateModelsForVariable(List<File> files, List<ModelMap> allModels, List<String> unusedModels, List<ModelMap> aliasModels, List<String> processedModels, CodegenProperty variable) {
        if (variable == null) {
            return;
        }

        final String schemaKey = calculateModelKey(variable.getOpenApiType(), variable.getRef());
        Map<String, Schema> allSchemas = ModelUtils.getSchemas(this.openAPI);

View on GitHub (pinned to fcec517be3)

Solutions

  1. Check the chained 'Caused by:' - FileNotFoundException for a .mustache template points to a missing template; IOException points to a filesystem problem; MustacheException points to template data.
  2. If using --template-dir, copy ALL templates shipped with the generator (src/main/resources/<generator>/) into the override, not just the ones you edited.
  3. Ensure the output folder exists and is writable by the generating process (mkdir -p; check permissions/AV locks), and rerun into a clean output directory to rule out stale locked files.
  4. Isolate the failing sub-step with --global-property modelDocs=false or modelTests=false (models-only run) to confirm which of the three writes fails.
  5. Align template and engine versions with the generator release, or upgrade both together - mismatched template/bundle pairs are a recurring cause.

Example fix

# before: full run fails on one bad template step
openapi-generator generate -g java -i api.yaml -o out --template-dir my-tpl
# after: isolate model docs/tests while fixing the template
openapi-generator generate -g java -i api.yaml -o out --template-dir my-tpl \
  --global-property modelDocs=false,modelTests=false
Defensive patterns

Strategy: try-catch

Validate before calling

// Pre-flight: output dir writable, and all declared templates resolvable
Path out = Path.of(config.outputFolder());
Files.createDirectories(out);
if (!Files.isWritable(out)) throw new IllegalStateException("Output not writable: " + out);
for (SupportingFile unused : config.supportingFiles()) { } // models use modelTemplateFiles():
for (String tpl : config.modelTemplateFiles().keySet()) {
    if (config.getTemplateDir() != null && !Files.exists(Path.of(config.getTemplateDir(), tpl))) {
        throw new IllegalStateException("Missing model template override: " + tpl);
    }
}

Try / catch

try {
    generator.opts(input).generate();
} catch (RuntimeException e) {
    if (e.getMessage() != null && e.getMessage().startsWith("Could not generate model")) {
        // cause chain holds IOException (filesystem) vs template exception (override gap)
        Throwable root = deepestCause(e);
        if (root instanceof java.io.IOException) { /* clean output dir, retry once */ }
        else { /* restore missing template from generator resources */ }
    }
}

Prevention

When it happens

Trigger: A model template referenced by config.modelTemplateFiles()/modelTestTemplateFiles()/modelDocTemplateFiles() missing from a --template-dir override; a custom Mustache lambda throwing on this model's data (e.g. null enum values, absent vendorExtension the lambda expects); the computed output filename being unwritable (illegal characters on the OS, path too long, output directory not writable or locked); template data shape changed after a generator upgrade while templates were pinned old.

Common situations: Copying only some templates into a --template-dir and forgetting model test/doc templates; running on CI where the output directory is read-only or owned by another user; Windows path-length or reserved-name limits with long model names; custom generator templates written for 5.x used against 6.x where the model bundle changed.

Related errors


AI-assisted analysis of OpenAPITools/openapi-generator@fcec517be3 (2026-08-22). Data as JSON: /api/errors/50f8e337687fff2e. Report an issue: GitHub.