4

I'm working on a web api using dotnet core 2.2 and we want to catch serialization exception and return a 400 badRequest to distinguish from the validation errors 422UnprocessableEntity. We tried to create an exception handler

public void JsonSerializerExceptionHandler(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
    {
        args.ErrorContext.Handled = true;
        var errorContext = args.ErrorContext;
        if (errorContext == null)
        {
            return;
        }

        var error = errorContext.Error;
        throw new SerializationException(error.Message, error.InnerException);
    }

but when it throw it throw an other Exception of type InvalidOperationException with message

Current error context error is different to requested error.

We tried different approach but can't find a solution. Can someone help?

2
  • Im unsure why you are trying to achieve this. I would just wrap my serialization code in a try catch and if you are looking for serialization errors just add a specific catch block for that. You can go as far as writing a middleware that specifically catches these anywhere in the MVC layer. Commented Feb 7, 2019 at 8:03
  • We are trying to achieve this because it is a request from the client, Json.net does not throw exceptions by itself, if I remove the last line it doesn't throw at all. Commented Feb 7, 2019 at 12:50

1 Answer 1

1

Maybe my solution will be useful for somebody. I need to catch JSON.NET serialization or deserialization exception and handle it in my .NET Core middleware.

Add rethrow json.net exception in JSON.NET SerializerSettings

services.AddControllers().AddNewtonsoftJson(options => {


    //your options here
 

    options.SerializerSettings.Error += (sender, args) => throw args.ErrorContext.Error;

});

Add catch on middleware handler and override JsonSerializationException:

if (exception is JsonSerializationException)
{
    var exceptionMessage = exception.InnerException != null ? 
       exception.InnerException.Message : exception.Message;

    exception = new BadRequestException(ApiErrorCode.InvalidResourceModel,
      exceptionMessage);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I have occasionally hit issues where an action parameter was null. They are frustrating to debug, but so far have been very straight-forward. This one was very difficult, so I went in search of info on how to see deserialization error details. This post was VERY useful, thank you! Upvoted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.