Skip to content

Commit b09c109

Browse files
CopilotScarletKuro
andcommitted
Improve error handling in DateOnly and TimeOnly converters
Co-authored-by: ScarletKuro <19953225+ScarletKuro@users.noreply.github.com>
1 parent d49b3c2 commit b09c109

2 files changed

Lines changed: 18 additions & 4 deletions

File tree

src/Scarlet.System.Text.Json.DateTimeConverter/Converters/DateOnlyConverter.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,15 @@ public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, Jso
3535
}
3636

3737
// Fallback to reading as DateTime and converting to DateOnly
38-
var dateTime = reader.GetDateTime();
39-
return DateOnly.FromDateTime(dateTime);
38+
try
39+
{
40+
var dateTime = reader.GetDateTime();
41+
return DateOnly.FromDateTime(dateTime);
42+
}
43+
catch (Exception ex) when (ex is FormatException || ex is InvalidOperationException)
44+
{
45+
throw new JsonException($"Unable to convert token to DateOnly using format '{_format}'.", ex);
46+
}
4047
}
4148

4249
/// <summary>

src/Scarlet.System.Text.Json.DateTimeConverter/Converters/TimeOnlyConverter.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,15 @@ public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, Jso
3535
}
3636

3737
// Fallback to reading as DateTime and converting to TimeOnly
38-
var dateTime = reader.GetDateTime();
39-
return TimeOnly.FromDateTime(dateTime);
38+
try
39+
{
40+
var dateTime = reader.GetDateTime();
41+
return TimeOnly.FromDateTime(dateTime);
42+
}
43+
catch (Exception ex) when (ex is FormatException || ex is InvalidOperationException)
44+
{
45+
throw new JsonException($"Unable to convert token to TimeOnly using format '{_format}'.", ex);
46+
}
4047
}
4148

4249
/// <summary>

0 commit comments

Comments
 (0)