Skip to content

Add a Program.Main() override with a throwOnError parameter #3140

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion src/Playwright/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

using System;
using System.Diagnostics;
using System.IO;
using Microsoft.Playwright.Helpers;

namespace Microsoft.Playwright;
Expand All @@ -37,14 +38,19 @@ public static int Main(string[] args)
}

public int Run(string[] args)
{
return Run(args, throwOnError: false);
}

public int Run(string[] args, bool throwOnError)
{
Func<string?, string> getArgs;
string executablePath;
try
{
(executablePath, getArgs) = Driver.GetExecutablePath();
}
catch
catch when (!throwOnError)
{
return PrintError("Microsoft.Playwright assembly was found, but is missing required assets. Please ensure to build your project before running Playwright tool.");
}
Expand All @@ -55,6 +61,8 @@ public int Run(string[] args)
// This works after net8.0-preview-4
// https://github.com/dotnet/runtime/pull/82662
WindowStyle = ProcessWindowStyle.Hidden,
RedirectStandardOutput = throwOnError,
RedirectStandardError = throwOnError,
};
foreach (var pair in Driver.EnvironmentVariables)
{
Expand All @@ -66,9 +74,26 @@ public int Run(string[] args)
StartInfo = playwrightStartInfo,
};

using var pwOutput = new StringWriter();
if (throwOnError)
{
pwProcess.OutputDataReceived += (_, eventArgs) => pwOutput.WriteLine(eventArgs.Data);
pwProcess.ErrorDataReceived += (_, eventArgs) => pwOutput.WriteLine(eventArgs.Data);
}
pwProcess.Start();
if (throwOnError)
{
pwProcess.BeginOutputReadLine();
pwProcess.BeginErrorReadLine();
}

pwProcess.WaitForExit();

if (pwProcess.ExitCode != 0 && throwOnError)
{
throw new PlaywrightException($"Failed to run {playwrightStartInfo.FileName} {playwrightStartInfo.Arguments}{Environment.NewLine}{pwOutput.ToString().Trim()}");
}

return pwProcess.ExitCode;
}

Expand Down
Loading