Skip to content

Commit

Permalink
Avoid uncaught exceptions from OnExit handler. (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
tmds authored Jun 24, 2024
1 parent bfdf6a9 commit 499af3b
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
25 changes: 20 additions & 5 deletions src/Tmds.ExecFunction/ExecFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,17 +136,31 @@ private static (Process process, Task exitedTask) Start(MethodInfo method, strin
tcs = new TaskCompletionSource<bool>();
}

if (options.OnExit != null || tcs != null)
if ((options.OnExit != null && !!waitForExit) || tcs != null)
{
process.EnableRaisingEvents = true;
process.Exited += (_1, _2) =>
{
options.OnExit(process);

if (tcs != null)
{
tcs?.SetResult(true);
process.Dispose();
try
{
options.OnExit?.Invoke(process);
tcs.SetResult(true);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
finally
{
process.Dispose();
}
}
else if (!waitForExit)
{
// If this throws, the exception is uncaught.
options.OnExit?.Invoke(process);
}
};
}
Expand All @@ -156,6 +170,7 @@ private static (Process process, Task exitedTask) Start(MethodInfo method, strin
if (waitForExit)
{
process.WaitForExit();
options.OnExit?.Invoke(process);
}

return (process, tcs?.Task);
Expand Down
27 changes: 27 additions & 0 deletions test/Tmds.ExecFunction.Tests/UnitTest1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,5 +131,32 @@ await FunctionExecutor.RunAsync(
Assert.Equal("hello world", outText);
}

[Fact]
public async Task RunAsyncCapturesOnExitException()
{
await Assert.ThrowsAsync<ApplicationException>(() =>
ExecFunction.RunAsync(
() => 42,
o =>
{
o.OnExit = process => { throw new ApplicationException(); };
}
));
}

[Fact]
public void RunThrowsOnExitException()
{
Assert.Throws<ApplicationException>(() =>
{
ExecFunction.Run(
() => 42,
o =>
{
o.OnExit = process => { throw new ApplicationException(); };
}
);
});
}
}
}

0 comments on commit 499af3b

Please sign in to comment.