Skip to content

Commit 95ebe1b

Browse files
committed
Allow WarningEmitted handlers to throw exceptions
1 parent 4e8f2f9 commit 95ebe1b

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

src/Laylua.Tests/Tests/Library/LuaTests.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,4 +428,29 @@ public void Warn_CustomControlMessage_TriggersWarningEventWithIsControlTrue()
428428
// Assert
429429
Assert.That(actualWarnings, Is.EqualTo(expectedWarnings));
430430
}
431+
432+
[Test]
433+
public void Warn_ThrowingExceptionEventHandler_Errors()
434+
{
435+
// Arrange
436+
const string ExceptionMessage = "Warning event handler exception.";
437+
438+
Lua.OpenLibrary(LuaLibraries.Standard.Base);
439+
Lua.WarningEmitted += static (_, _) => throw new Exception(ExceptionMessage);
440+
441+
// Act & Assert
442+
Assert.That(() => Lua.Execute("warn('')"), Throws.TypeOf<LuaException>().With.InnerException.Not.Null.And.InnerException.Message.EqualTo(ExceptionMessage));
443+
}
444+
445+
[Test]
446+
public void EmitWarning_ThrowingExceptionEventHandler_Throws()
447+
{
448+
// Arrange
449+
const string ExceptionMessage = "Warning event handler exception.";
450+
451+
Lua.WarningEmitted += static (_, _) => throw new Exception(ExceptionMessage);
452+
453+
// Act & Assert
454+
Assert.That(() => Lua.EmitWarning(""), Throws.TypeOf<LuaPanicException>().With.InnerException.Not.Null.And.InnerException.Message.EqualTo(ExceptionMessage));
455+
}
431456
}

src/Laylua/Library/Lua.Warnings.cs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,6 @@ public sealed unsafe partial class Lua
2828
/// See <a href="https://www.lua.org/manual/5.4/manual.html#2.3">Error Handling (Lua manual)</a> and
2929
/// <a href="https://www.lua.org/manual/5.4/manual.html#pdf-warn"><c>warn (msg1, ···) (Lua Manual)</c></a> for more information about warnings.
3030
/// </summary>
31-
/// <remarks>
32-
/// Subscribed event handlers must not throw any exceptions.
33-
/// </remarks>
3431
public event LuaWarningEventHandler? WarningEmitted;
3532

3633
private MemoryStream? _warningBuffer;
@@ -99,7 +96,14 @@ static void InvokeWarningEmitted(Lua lua, ReadOnlySpan<byte> msgSpan)
9996

10097
using (message)
10198
{
102-
lua.WarningEmitted?.Invoke(lua, new LuaWarningEmittedEventArgs(message));
99+
try
100+
{
101+
lua.WarningEmitted?.Invoke(lua, new LuaWarningEmittedEventArgs(message));
102+
}
103+
catch (Exception ex)
104+
{
105+
LuaException.RaiseErrorInfo(lua.GetStatePointer(), "An exception occurred while invoking the warning event.", ex);
106+
}
103107
}
104108
}
105109

0 commit comments

Comments
 (0)