When WebApi serialization fails I would like the exception to bubble up not null my parameter

StackOverflow https://stackoverflow.com/questions/23529770

  •  17-07-2023
  •  | 
  •  

Question

I have a some custom converters that have been added to the SerializationSettings for my WebApi project. When I throw an exception inside one of the these converters, I still get a call to the Action. Depending on which converter failed the body parameter can be null or the default value set. What am I missing that can cause the webapi throw that error so I can deal with it at a more global level?

webapi verison: 4.0.30506

json.net version : 5.0.8

Was it helpful?

Solution

I had the same problem (but there is a work around for it). You could put a flag into the http context and access it later in the web api and handle it there. You cannot throw an exception from the custom serializer and capture it in the web api. It just ignores the exception and forces to the execution to the end of the ReadJson function if you are trying to over ride this.

you can use this for http context HttpContext.Current.Items["Error Info"] = "Some Error Info”

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer){
     ...            
     throw new Exception();
     ...

     ///comes here to the end directly                     
    }

OTHER TIPS

If you are using owin web api then the HttpContext.Current is null. You can use this package - OwinRequestScopeContext which allows you to use the context which is also per request.

for example set the error in the JsonConverter:

OwinRequestScopeContext.Current.Items["error"] = exception;

And then get the error in your controller:

var ex = OwinRequestScopeContext.Current.Items["error"] as Exception;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top