diff --git a/projects/RabbitMQ.Client/client/impl/WireFormatting.cs b/projects/RabbitMQ.Client/client/impl/WireFormatting.cs index d97262b607..8d269b18f4 100644 --- a/projects/RabbitMQ.Client/client/impl/WireFormatting.cs +++ b/projects/RabbitMQ.Client/client/impl/WireFormatting.cs @@ -435,9 +435,17 @@ public static unsafe int WriteShortstr(Span span, string val) fixed (char* chars = val) fixed (byte* bytes = &span.Slice(1).GetPinnableReference()) { - int bytesWritten = Encoding.UTF8.GetBytes(chars, val.Length, bytes, maxLength); - span[0] = (byte)bytesWritten; - return bytesWritten + 1; + try + { + int bytesWritten = Encoding.UTF8.GetBytes(chars, val.Length, bytes, maxLength); + span[0] = (byte)bytesWritten; + return bytesWritten + 1; + } + catch (ArgumentException) + { + throw new ArgumentOutOfRangeException(nameof(val), val, $"Value exceeds the maximum allowed length of {maxLength} bytes."); + } + } } diff --git a/projects/Unit/TestFieldTableFormatting.cs b/projects/Unit/TestFieldTableFormatting.cs index 5da8a035b3..1025adb7a4 100644 --- a/projects/Unit/TestFieldTableFormatting.cs +++ b/projects/Unit/TestFieldTableFormatting.cs @@ -139,7 +139,7 @@ [new string('A', TooLarge)] = null int bytesNeeded = WireFormatting.GetTableByteCount(t); byte[] bytes = new byte[bytesNeeded]; - Assert.Throws(() => WireFormatting.WriteTable(bytes, t)); + Assert.Throws(() => WireFormatting.WriteTable(bytes, t)); } [Test]