woocommerce / woocommerce-android

WooCommerce Android app
https://www.woocommerce.com/mobile
GNU General Public License v2.0
277 stars 135 forks source link

Catch `IllegalStateException` when attempting to parse wrong formatted product image jsons #11589

Open JorgeMucientes opened 5 months ago

JorgeMucientes commented 5 months ago

We are experiencing some crashes when attempting to parse the following json section from a product model:

    "images": [
      {
        "id": 795,
        "date_created": "2017-03-23T14:03:08",
        "date_created_gmt": "2017-03-23T20:03:08",
        "date_modified": "2017-03-23T14:03:08",
        "date_modified_gmt": "2017-03-23T20:03:08",
        "src": "https://example.com/wp-content/uploads/2017/03/T_4_front-11.jpg",
        "name": "",
        "alt": ""
      },
      {

The reason for the crash is because there seems to be some plugin (we don't know which one) that is modifying the structure of that json, returning something like this, instead of the json above:

{
   "15752":"https://passofino.com/wp-content/uploads/2024/03/pantofi-decupati-din-piele-yasmina-donna-0.jpg",
   "15754":"https://passofino.com/wp-content/uploads/2024/03/pantofi-decupati-din-piele-yasmina-donna-1.jpg",
   "15755":"https://passofino.com/wp-content/uploads/2024/03/pantofi-decupati-din-piele-yasmina-donna-2.jpg",
...
}

This causes the following code to crash, because we are only catching JsonParseException.

    fun getFirstImageUrl(): String? {
        try {
            if (images.isNotEmpty()) {
                Gson().fromJson(images, JsonElement::class.java).asJsonArray.firstOrNull { jsonElement ->
                    return (jsonElement.asJsonObject).getString("src")
                }
            }
        } catch (e: JsonParseException) {
            AppLog.e(T.API, e)
        }
        return null
    }

The idea of this issue is 2 things:

dangermattic commented 5 months ago

🚫 Please add a type label (e.g. type: enhancement) and a feature label (e.g. feature: stats) to this issue.