Return generic error message for odata errors

Viewed 37

I have an asp.net core application with the following odata configuration

services.AddControllers()
        .AddOData(oDataOptions =>
            oDataOptions.AddRouteComponents("api/import/odata", GetEdmModel())
                .SetMaxTop(5000)
                .Filter()
                .Select()
                .Count()
                .Expand()
                .OrderBy()
                .SkipToken());

Here's the Controller call

[EnableQuery(MaxExpansionDepth = 5)]
public IQueryable<TransformedEntity> Get()
{
    return _importContext.TransformedEntities.AsQueryable();
}       

The api works as expected. Issue:

https://localhost:7245/api/import/odata/TransformedEntities?$format=json&$count=true&$expand=ImportStatus&$top=10&$filter=ImportId%20eq%20210a

At the end of the url I have added an invalid character which fails due to incorrect parameters which is expected . Here's the error that it throws:

{"error":{"code":"","message":"The query specified in the URI is not valid. Syntax error at position 16 in 'ImportId eq 210a'.","details":[],"innererror":{"message":"Syntax error at position 16 in 'ImportId eq 210a'.","type":"Microsoft.OData.ODataException","stacktrace":"   at Microsoft.OData.UriParser.ExpressionLexer.ValidateToken(ExpressionTokenKind t)\r\n   at Microsoft.OData.UriParser.UriQueryExpressionParser.ParseExpressionText(String expressionText)\r\n   at Microsoft.OData.UriParser.ODataQueryOptionParser.ParseFilterImplementation(String filter, ODataUriParserConfiguration configuration, ODataPathInfo odataPathInfo)\r\n   at Microsoft.OData.UriParser.ODataQueryOptionParser.ParseFilter()\r\n   at Microsoft.AspNetCore.OData.Query.FilterQueryOption.get_FilterClause()\r\n   at Microsoft.AspNetCore.OData.Query.Validator.FilterQueryValidator.Validate(FilterQueryOption filterQueryOption, ODataValidationSettings settings)\r\n   at Microsoft.AspNetCore.OData.Query.Validator.ODataQueryValidator.Validate(ODataQueryOptions options, ODataValidationSettings validationSettings)\r\n   at Microsoft.AspNetCore.OData.Query.EnableQueryAttribute.ValidateQuery(HttpRequest request, ODataQueryOptions queryOptions)\r\n   at Microsoft.AspNetCore.OData.Query.EnableQueryAttribute.OnActionExecuting(ActionExecutingContext actionExecutingContext)"}}}

If i extend EnableQueryAttribute to create a custom attribute & use the same in each of the method call instead of the default EnableQueryAttribute ,it works just fine. But that would require adding it to all the individual method calls.

Is there a setting to handle it globally within Startup.cs to throw a generic error message with regards to odata errors.

Any input is appreciated.

0 Answers
Related