JeffreySu/WeiXinMPSDK · error · ArgumentOutOfRangeException

ArgumentOutOfRangeException (length must be >= 0)

Error message

ArgumentOutOfRangeException (length must be >= 0)

What it means

TenPayV3Util.BuildRandomStr(length) generates a random numeric string of the given length. The library explicitly rejects negative lengths with ArgumentOutOfRangeException because StringBuilder and the generation loop cannot produce a negative-length string.

Solutions

  1. Clamp or validate the length before calling: if (length < 0) length = 0;
  2. Trace where the negative value originates (usually an arithmetic mistake on an input) and fix the source
  3. Use a fixed constant length (e.g. BuildRandomStr(32)) for payment nonces as TenPay docs require

Example fix

// before
var nonce = TenPayV3Util.BuildRandomStr(orderId.Length - 10);
// after
var len = Math.Max(0, orderId.Length - 10);
var nonce = TenPayV3Util.BuildRandomStr(len);
Defensive patterns

Strategy: validation

Validate before calling

if (length < 0) throw new ArgumentException("length must be >= 0", nameof(length)); var nonce = TenPayV3Util.BuildRandomStr(length);

Type guard

static bool IsValidRandomLength(int length) => length >= 0;

Try / catch

try { nonce = TenPayV3Util.BuildRandomStr(len); } catch (ArgumentOutOfRangeException) { nonce = TenPayV3Util.BuildRandomStr(32); }

Prevention

When it happens

Trigger: Passing a negative int to BuildRandomStr, typically a computed length from a variable (e.g. length = str.Length where str is empty minus an offset) or a caller-supplied request parameter.

Common situations: Dynamic nonce generation where the length derives from user input or parsed config that ends up negative; copy-paste of code where a constant was meant.

Understand the failure class

Background: "value must be between 0 and 1" / "out of range" / "must not be negative" errors: fixing range-validation failures across open-source libraries — this error's family across 42 libraries.

Related errors


AI-assisted analysis of JeffreySu/WeiXinMPSDK@be573f6f94 (2026-09-12). Data as JSON: /api/errors/1da2a7c8f39ffa25. Report an issue: GitHub.

Appendix: source

Thrown at src/Senparc.Weixin.TenPay/Senparc.Weixin.TenPayV3/TenPayV3Util.cs:164

        /// 取时间戳生成随即数,替换交易单号中的后10位流水号
        /// </summary>
        /// <returns></returns>
        public static UInt32 UnixStamp()
        {
            TimeSpan ts = SystemTime.Now - new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);
            return Convert.ToUInt32(ts.TotalSeconds);
        }

        /// <summary>
        /// 取随机数
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string BuildRandomStr(int length)
        {
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length));
            }

            var result = new StringBuilder(length);
            var randomByte = new byte[1];
            const int UnbiasedUpperBound = 250;//最大的不大于 256 且可被 10 整除的数
            using (var randomNumberGenerator = RandomNumberGenerator.Create())
            {
                for (var i = 0; i < length; i++)
                {
                    do
                    {
                        randomNumberGenerator.GetBytes(randomByte);
                    }
                    while (randomByte[0] >= UnbiasedUpperBound);

                    result.Append((char)('0' + randomByte[0] % 10));
                }
            }

View on GitHub (pinned to be573f6f94)