I am creating an ASP.Net 5 application with MVC 6, using .Net 4.5.1. I have a POST method that uses a FromBody parameter to get the object automatically.
[HttpPost]
public IActionResult Insert([FromBody]Agent agent)
{
try
{
var id = service.Insert(agent);
return Ok(id);
}
catch (Exception ex)
{
return HttpBadRequest(ex);
}
}
This is just a proof a concept, I won't return only the id on success or the full exception on error.
When a valid JSON is sent everything works fine. However when an invalid JSON is sent, I get an exception during debug:
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
Additional information: After parsing a value an unexpected character was encountered: l. Path 'Name', line 2, position 20.
The problem is that after this error, the method is called normally, but with a null parameter, and the exception doesn't propagate.
I could check for null and return a generic message, but that is not as useful as the original message, which has important information, such as the tag name and position of the invalid character.
So I want to capture this exception and return it to the HTTP caller. How do I do that? Something like this:
{"error": "After parsing a value an unexpected character was encountered: l. Path 'Name', line 2, position 20"}
I know I could capture and deserialize the JSON manually inside a try/catch block, but that is not acceptable for me. I want to do it and continue using FromBody, which I find very productive.