Skip to content

Commit 531c2d3

Browse files
committed
fix: catch invalid enums
1 parent 79dc08e commit 531c2d3

3 files changed

Lines changed: 21 additions & 3 deletions

File tree

QueryKit.IntegrationTests/Tests/DatabaseSortingTests.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ namespace QueryKit.IntegrationTests.Tests;
33
using Bogus;
44
using FluentAssertions;
55
using Microsoft.EntityFrameworkCore;
6+
using QueryKit.Exceptions;
67
using SharedTestingHelper.Fakes;
78
using WebApiTestProject.Entities;
89

@@ -165,7 +166,7 @@ public async Task a_prop_with_hasconversion_must_match_that_configuration()
165166
var act = () => appliedQueryable.ToListAsync();
166167

167168
// Assert
168-
await act.Should().ThrowAsync<InvalidOperationException>();
169+
await act.Should().ThrowAsync<ParsingException>();
169170
}
170171

171172
[Fact]
@@ -242,4 +243,4 @@ public async Task can_sort_items_with_null_value_property()
242243
people[2].Id.Should().Be(fakePersonFour.Id);
243244
people[3].Id.Should().Be(fakePersonThree.Id);
244245
}
245-
}
246+
}

QueryKit.UnitTests/FilterParserTests.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -799,5 +799,14 @@ public void primitive_collection_does_not_have_case_insensitive()
799799
filterExpression.ToString().Should()
800800
.Be(""""x => x.Tags.Any(z => (z.ToLower() != "winner".ToLower()))"""");
801801
}
802+
803+
[Fact]
804+
public void can_throw_exception_when_invalid_enum_value()
805+
{
806+
var input = $"""BirthMonth == invalid""";
807+
var act = () => FilterParser.ParseFilter<TestingPerson>(input);
808+
act.Should().Throw<ParsingException>()
809+
.WithMessage("There was a parsing failure, likely due to an invalid comparison or logical operator. You may also be missing double quotes surrounding a string or guid.");
810+
}
802811
}
803812

QueryKit/FilterParser.cs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ public static Expression<Func<T, bool>> ParseFilter<T>(string input, IQueryKitCo
3131
{
3232
expr = ExprParser<T>(parameter, config).End().Parse(input);
3333
}
34+
catch (InvalidOperationException e) {
35+
throw new ParsingException(e);
36+
}
3437
catch (ParseException e)
3538
{
3639
throw new ParsingException(e);
@@ -314,7 +317,12 @@ private static Expression CreateRightExprFromType(Type leftExprType, string righ
314317
return Expression.Constant(null, rawType);
315318
}
316319

317-
var enumValue = Enum.Parse(enumType, right);
320+
var parsed = Enum.TryParse(enumType, right, out var enumValue);
321+
if (!parsed)
322+
{
323+
throw new InvalidOperationException($"Unsupported value '{right}' for type '{targetType.Name}'");
324+
}
325+
318326
var constant = Expression.Constant(enumValue, enumType);
319327

320328
if (rawType == enumType) return constant;

0 commit comments

Comments
 (0)