{"record":{"id":"b6cf6265ec487c6d","repo":"RicoSuter/NSwag","slug":"swagger-generation-failed-with-non-zero-exit-code-exitcode","errorCode":null,"errorMessage":"Swagger generation failed with non-zero exit code '{exitCode}'.","messagePattern":"Swagger generation failed with non-zero exit code '(.+?)'\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs","lineNumber":192,"sourceCode":"            }\n\n            var commandFile = Path.GetTempFileName();\n            var outputFile = Path.GetTempFileName();\n            File.WriteAllText(commandFile, JsonConvert.SerializeObject(this));\n            cleanupFiles.Add(commandFile);\n            cleanupFiles.Add(outputFile);\n\n            args.Add(commandFile);\n            args.Add(outputFile);\n            args.Add(projectMetadata.AssemblyName);\n            args.Add(toolDirectory);\n\n            try\n            {\n                var exitCode = await Exe.RunAsync(executable, args, verboseHost).ConfigureAwait(false);\n                if (exitCode != 0)\n                {\n                    throw new InvalidOperationException($\"Swagger generation failed with non-zero exit code '{exitCode}'.\");\n                }\n\n                host?.WriteMessage($\"Output written to {outputFile}.{Environment.NewLine}\");\n\n                var documentJson = File.ReadAllText(outputFile);\n                var document = await OpenApiDocument.FromJsonAsync(documentJson, null).ConfigureAwait(false);\n                await this.TryWriteDocumentOutputAsync(host, NewLineBehavior, () => document).ConfigureAwait(false);\n                return document;\n            }\n            finally\n            {\n                TryDeleteFiles(cleanupFiles);\n            }\n        }\n\n        internal string ChangeWorkingDirectoryAndSetAspNetCoreEnvironment()\n        {\n            if (!string.IsNullOrEmpty(AspNetCoreEnvironment))","sourceCodeStart":174,"sourceCodeEnd":210,"githubUrl":"https://github.com/RicoSuter/NSwag/blob/63daf8fcc3a25151b62eb4b326a1e8ea048a0d41/src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs#L174-L210","documentation":"NSwag launches the project in a separate process (via the AspNetCore.Launcher) that generates the OpenAPI document and writes it to a temp file. RunAsync checks the process exit code and throws this error when it is non-zero, meaning the child application crashed, failed to start, or threw during Swagger generation. The real cause is in the child process output (visible with verbose logging).","triggerScenarios":"Exe.RunAsync returns any exit code other than 0 after running the launcher against the target assembly — e.g. the app throws in Startup/Program, required services fail, DLLs are missing, or the app exits early without writing the output file.","commonSituations":"Startup.cs throws (bad connection string, missing config); DI fails to resolve controllers/swagger services; version mismatch between NSwag and Microsoft.AspNetCore packages; running an app built for a different runtime than the one installed; unhandled exception in app initialization.","solutions":["Run with /verbose:true and read the child process's console output to find the actual exception in the target app.","Fix the underlying Startup/Program failure (missing config, DI registration, migrations) that makes the app exit non-zero.","Ensure NSwag package versions match your ASP.NET Core version (e.g. use the NSwag.AspNetCore package line matching your runtime).","Verify the runtime installed on the machine matches the project's target framework.","Try running the project directly (`dotnet run`) to reproduce and debug the startup exception."],"exampleFix":"// before\nnswag aspnetcore2openapi /project:MyApi.csproj\n// after (verbose to see the real failure)\nnswag aspnetcore2openapi /project:MyApi.csproj /verbose:true","handlingStrategy":"try-catch","validationCode":"// run the app standalone first to surface startup errors\ndotnet run --project src/MyApi  // must start cleanly before NSwag can generate","typeGuard":null,"tryCatchPattern":"try\n{\n    await command.RunAsync(processor, host);\n}\ncatch (InvalidOperationException ex) when (ex.Message.StartsWith(\"Swagger generation failed\"))\n{\n    // re-run with /verbose:true or inspect launcher logs for the child's real exception\n}","preventionTips":["Always generate with /verbose:true in CI so child-process exceptions are captured.","Keep NSwag.AspNetCore package versions aligned with your ASP.NET Core runtime.","Smoke-test `dotnet run` on the project before wiring spec generation into CI.","Ensure Program.cs/Startup has no environment-dependent failures (missing secrets, DB connectivity)."],"tags":["process-exit-code","aspnetcore","swagger-generation"],"backgroundTag":"http-request-failed","analyzedSha":"63daf8fcc3a25151b62eb4b326a1e8ea048a0d41","analyzedAt":"2026-09-14T11:38:15.205Z","contentChangedAt":"2026-09-14T11:38:15.205Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}