Advanced NewtonsoftJson parsing error handling
DaveLaa opened this issue · 2 comments
Advanced Newtonsoft parsing error handling
I have a suggestion to the Microsoft.AspNetCore.Mvc.NewtonsoftJson project to improve the possibility of parsing error handling.
In my services project I have the need to be able to decide which parsing error of json objects sent to my service are tollerable and can be safely ignored. I achieve this goal by adding an error handler in the SerializerSettings of NewtonsoftJson and setting the Handled property to true.
This was no problem as long as my service project was compiled against .Net Framework. But now we refactored the services to compile against .Net Core 5 and here I found out that there is no way to have this decision.
In my new Startup I added the NewtonsoftJson support and also my error handler like this:
public class Startup {
...
public void ConfigureServices( IServiceCollection services ) {
...
services.AddControllers().AddNewtonsoftJson( opts => {
...
opts.SerializerSettings.Error = ( sender, args ) => {
if(...){
...
args.ErrorContext.Handled = true;
}
};
} );
...
}
}
But whatever i declare handeld, the error was allways thrown anyways by the AspNet framework. I debugged the NewtonsoftJsonInputFormatter and found out that here all errors are passed to the ModelStateDictionary regardless of being handled before or not. More important is that the parsed model ist not returned (always return InputFormatterResult.Failure();) and my service entdpoint gets a null object instead. There is also no way to configure a different behaviour.
My suggestion ist now to look into the Handled property and ignore errors that are already handled by user in external code:
public class NewtonsoftJsonInputFormatter : TextInputFormatter, IInputFormatterExceptionPolicy
{
...
public override async Task<InputFormatterResult> ReadRequestBodyAsync(
...
void ErrorHandler(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs eventArgs)
{
>> if( eventArgs.ErrorContext.Handled ){
>> // Error was already handeld by User in external code
>> return;
>> }
successful = false;
....
}
}
...
}
Is it possible to implement this feature in future versions of .Net Core 5?
We've moved this issue to the Backlog milestone. This means that it is not going to be worked on for the coming release. We will reassess the backlog following the current release and consider this item at that time. To learn more about our issue management process and to have better expectation regarding different types of issues you can read our Triage Process.