RicoSuter/NSwag · error · InvalidOperationException

Swagger generation failed with non-zero exit code

Error message

Swagger generation failed with non-zero exit code '{exitCode}'.

What it means

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).

Solutions

  1. Run with /verbose:true and read the child process's console output to find the actual exception in the target app.
  2. Fix the underlying Startup/Program failure (missing config, DI registration, migrations) that makes the app exit non-zero.
  3. Ensure NSwag package versions match your ASP.NET Core version (e.g. use the NSwag.AspNetCore package line matching your runtime).
  4. Verify the runtime installed on the machine matches the project's target framework.
  5. Try running the project directly (`dotnet run`) to reproduce and debug the startup exception.

Example fix

// before
nswag aspnetcore2openapi /project:MyApi.csproj
// after (verbose to see the real failure)
nswag aspnetcore2openapi /project:MyApi.csproj /verbose:true
Defensive patterns

Strategy: try-catch

Validate before calling

// run the app standalone first to surface startup errors
dotnet run --project src/MyApi  // must start cleanly before NSwag can generate

Try / catch

try
{
    await command.RunAsync(processor, host);
}
catch (InvalidOperationException ex) when (ex.Message.StartsWith("Swagger generation failed"))
{
    // re-run with /verbose:true or inspect launcher logs for the child's real exception
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Understand the failure class

Background: 'Something went wrong' / 'Request failed (500)' / 'HTTP error! status: 404' — what failed HTTP requests actually mean and how to find the real cause — this error's family across 28 libraries.

Related errors


AI-assisted analysis of RicoSuter/NSwag@63daf8fcc3 (2026-09-14). Data as JSON: /api/errors/b6cf6265ec487c6d. Report an issue: GitHub.

Appendix: source

Thrown at src/NSwag.Commands/Commands/Generation/AspNetCore/AspNetCoreToOpenApiCommand.cs:192

            }

            var commandFile = Path.GetTempFileName();
            var outputFile = Path.GetTempFileName();
            File.WriteAllText(commandFile, JsonConvert.SerializeObject(this));
            cleanupFiles.Add(commandFile);
            cleanupFiles.Add(outputFile);

            args.Add(commandFile);
            args.Add(outputFile);
            args.Add(projectMetadata.AssemblyName);
            args.Add(toolDirectory);

            try
            {
                var exitCode = await Exe.RunAsync(executable, args, verboseHost).ConfigureAwait(false);
                if (exitCode != 0)
                {
                    throw new InvalidOperationException($"Swagger generation failed with non-zero exit code '{exitCode}'.");
                }

                host?.WriteMessage($"Output written to {outputFile}.{Environment.NewLine}");

                var documentJson = File.ReadAllText(outputFile);
                var document = await OpenApiDocument.FromJsonAsync(documentJson, null).ConfigureAwait(false);
                await this.TryWriteDocumentOutputAsync(host, NewLineBehavior, () => document).ConfigureAwait(false);
                return document;
            }
            finally
            {
                TryDeleteFiles(cleanupFiles);
            }
        }

        internal string ChangeWorkingDirectoryAndSetAspNetCoreEnvironment()
        {
            if (!string.IsNullOrEmpty(AspNetCoreEnvironment))

View on GitHub (pinned to 63daf8fcc3)