I am using Utf8 json library to deserialize my JSON using DeserializeAsync
method of JsonSerializer
class. And sometimes I am seeing it is throwing exception as -
Arithmetic operation resulted in an overflow.
So it looks like my JSON data has a value that's too large to fit in one of our object's properties causing this overflow exception. Below is the code I got where I am trying to print the json which is bad and causing this Arithmetic Overflow
error but it's not logging that JSON whenever this exception happens.
using (var content = httpResponseMessage.Content)
{
if (content == null) return (default(T), statusCode);
using (var responseStream = await httpResponseMessage.Content.ReadAsStreamAsync())
{
try
{
deserializedValue = await JsonSerializer.DeserializeAsync<T>(responseStream, formatResolver);
}
catch (Exception ex)
{
var bodyString = (ex as JsonParsingException)?.GetUnderlyingByteArrayUnsafe();
var error = (bodyString != null) ? $"Bad json: {Encoding.UTF8.GetString(bodyString)}" : "Cannot Deserialize JSON";
logger.logError(error, ex.Message, "Deserialization Exception", ex.StackTrace, (int)statusCode);
return (default(T), HttpStatusCode.BadRequest);
}
}
}
For some reason bodyString
is coming as null whenever this exception happens and that's why my condition is not getting evaluated to get the JSON body. My understanding was that it will throw JsonParsingException
but looks like it is throwing some other exception.
Is there any way to get JSON body whenever this exception happens? or maybe write this in a better way to get JSON whenever this exception happens efficiently?
You wrote that you got an "Arithmetic Overflow" error, so the actual type of exception in the catch is probably OverflowException
, not JsonParsingException
I think you should get bodyString
from responseStream
. You can reset the stream with responseStream.Position = 0
and read the body as a byte array from it.