glacasa / Mastonet

C# Library for Mastodon
MIT License
225 stars 36 forks source link

Better error reporting #111

Open Guacam-Ole opened 1 year ago

Guacam-Ole commented 1 year ago

I constantly receive errors like this:

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path $   at Newtonsoft.Json.JsonTextReader.ParseValue()
   at Newtonsoft.Json.JsonReader.ReadAndMoveToContent()
   at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
   at Mastonet.BaseHttpClient.TryDeserialize[T](String json)
   at Mastonet.BaseHttpClient.Post[T](String route, IEnumerable`1 data, IEnumerable`1 media)
   at BohnTemps.Mastodon.Toot.UploadMeda(MastodonClient client, Stream fileStream, String filename, String description) in D:\git\private\bohntemps\Bohntemps\Mastodon\Toot.cs:line 28

This is not an error of MastoNet but either of the API or simply my media (most likely). Nonetheless: The error message Unexpected character encountered while parsing value: <. Path does not really help me there. I assume instead of the expected response the API returns an error message that cannot be parsed into the expected objecttype.

Can we change the behaviour to have the original error response inside the Exception instead of the resulting Deserialization-Error?

Guacam-Ole commented 1 year ago

very simple suggestion to change this:

    private static T TryDeserialize<T>(string json)
    {
        if (json[0] == '{')
        {
            var error = JsonConvert.DeserializeObject<Error>(json);
            if (error != null && !string.IsNullOrEmpty(error.Description))
            {
                throw new ServerErrorException(error);
            }
        }

        try
        {
            return JsonConvert.DeserializeObject<T>(json)!;
        }
        catch (Exception ex)
        {
            ex.Data.Add("json", json);
            ex.Data.Add("type", typeof(T));
            throw;
        }
    }

Any objections against this? I assume this should not be too much overhead also don't expect that the json contains secrets. But I am open for discussion

13xforever commented 9 months ago

I have a workaround with custom derived type (you can do proper logging there, I'm simply tracking the last message for my particular scenario).