Skip to content

Commit e784ce7

Browse files
committed
Expose offset on TomlException
1 parent bdbecda commit e784ce7

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/Tomlyn.Tests/NewApiExceptionLocationTests.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using NUnit.Framework;
2+
using Tomlyn.Parsing;
23
using Tomlyn.Serialization;
34

45
namespace Tomlyn.Tests;
@@ -38,4 +39,27 @@ public void Parse_SyntaxError_IncludesLocation()
3839
Assert.That(ex.Column, Is.GreaterThan(0));
3940
Assert.That(ex.Message, Does.Contain("test.toml("));
4041
}
42+
43+
[Test]
44+
public void Parse_InvalidUtf8_IncludesByteOffset()
45+
{
46+
// "a = " followed by an invalid UTF-8 sequence: 0xC3 0x28
47+
var bytes = new byte[] { (byte)'a', (byte)' ', (byte)'=', (byte)' ', 0xC3, 0x28, (byte)'\n' };
48+
var options = new TomlSerializerOptions { SourceName = "utf8.toml" };
49+
50+
var parser = TomlParser.Create(bytes, options);
51+
var ex = Assert.Throws<TomlException>(() =>
52+
{
53+
while (parser.MoveNext())
54+
{
55+
}
56+
});
57+
58+
Assert.That(ex, Is.Not.Null);
59+
Assert.That(ex!.Span.HasValue, Is.True);
60+
Assert.That(ex.Offset, Is.EqualTo(4));
61+
Assert.That(ex.Line, Is.EqualTo(1));
62+
Assert.That(ex.Column, Is.EqualTo(5));
63+
Assert.That(ex.Message, Does.Contain("utf8.toml("));
64+
}
4165
}

src/Tomlyn/TomlException.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,14 @@ public TomlException(TomlSourceSpan span, string message, Exception? innerExcept
7272
/// </summary>
7373
public int Column => Span?.Start.Column + 1 ?? 0;
7474

75+
/// <summary>
76+
/// Gets the 0-based offset associated with this exception, or 0 when unknown.
77+
/// </summary>
78+
/// <remarks>
79+
/// When parsing UTF-8 inputs, this offset represents a byte offset. When parsing string inputs, this offset represents a character offset.
80+
/// </remarks>
81+
public int Offset => Span?.Offset ?? 0;
82+
7583
private static string Format(TomlSourceSpan span, string message)
7684
{
7785
return $"{span.ToStringSimple()} : error : {message}";

0 commit comments

Comments
 (0)