0

If exception is thrown in my custom JsonConverter, I want to stop the request and return the error to the client. The problem is that if an exception happens in the converter, the controller method gets the parameter as null and I lose the exception. How can I stop the request from getting to the controller or get the occurred exception from JsonConverter in the controller? Or any other idea..

My converter similar to this post: How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

public class MyJsonConverter : JsonConverter
{
 protected override Person Create(Type objectType, JObject jObject)
    {
        Throw new Exception();
    }
}

My controller:

Public class MyController : ApiController
 {   
     Public IHttpResuls Post(Person p)   
     {
        ...   
     } 
 }
Community
  • 1
  • 1
Greg Oks
  • 2,700
  • 4
  • 35
  • 41

1 Answers1

0

I have a solution. Since the HttpContext.Current is null in OWIN web api. 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;
Greg Oks
  • 2,700
  • 4
  • 35
  • 41