openfoodfacts / openfoodfacts-dart

Open Food Facts API Wrapper
https://pub.dev/packages/openfoodfacts
Apache License 2.0
167 stars 67 forks source link

Format Exception When searching #518

Open Zubi1001 opened 2 years ago

Zubi1001 commented 2 years ago

Describe the bug A clear and concise description of what the bug is.

My parameters are ["Olive","Oil"]


  Future<SearchResult?> searchForProduct(List<String> searchTerms) async {
    try {
      ProductSearchQueryConfiguration configuration =
          ProductSearchQueryConfiguration(parametersList: [
        SearchTerms(terms: searchTerms),
        const SortBy(option: SortOption.POPULARITY)
      ], fields: [
        ProductField.ALL,
      ], language: OpenFoodFactsLanguage.ENGLISH);

      SearchResult result = await OpenFoodAPIClient.searchProducts(
          uc.openFoodUser, configuration,
          queryType: QueryType.TEST);

      return result;
    } catch (e, stacktrace) {
      log(e.toString());
      print(stacktrace);
      return null;
    }
  }

Expected behavior A clear and concise description of what you expected to happen.

**```
[log] FormatException: Unexpected character (at character 1)
      <!-- start templates/web/common/site_layout.tt.html -->
      ^
flutter: #0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1383:5)
#1      _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1250:9)
#2      _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:915:22)
#3      _parseJson (dart:convert-patch/convert_patch.dart:35:10)
#4      JsonDecoder.convert (dart:convert/json.dart:612:36)
#5      JsonCodec.decode (dart:convert/json.dart:216:41)
#6      OpenFoodAPIClient.getProducts
package:openfoodfacts/openfoodfacts.dart:312
<asynchronous suspension>
#7      FoodService.searchForProduct
package:affili_fit/…/foodService/food_service.dart:36
<asynchronous suspension>
#8      _TestGroundState.build.<anonymous closure>
package:affili_fit/main.dart:61
<asynchronous suspension>
```**

package information: Openfoodfacts package version:

Additional context Add any other context about the problem here.

monsieurtanuki commented 2 years ago

Hi @Zubi1001!

I've just tested and that's OK for me:

Basically the error you get is because we expect json data, and obviously something bad happened on the TEST server that did not return json data. Could be a timeout. Could be that your user is not a TEST user, but a PROD user.

Feel free to close the issue if solved.

For the record, my code:

      final ProductSearchQueryConfiguration configuration =
          ProductSearchQueryConfiguration(
        parametersList: [
          SearchTerms(terms: ["Olive", "Oil"]),
          const SortBy(option: SortOption.POPULARITY)
        ],
        fields: [ProductField.ALL],
        language: OpenFoodFactsLanguage.ENGLISH,
      );

      final SearchResult result = await OpenFoodAPIClient.searchProducts(
        TestConstants.TEST_USER,
        configuration,
        queryType: QueryType.TEST,
      );

      expect(result.products!.length, 24); // page 1
      print('results: ${result.count}'); // 285
Zubi1001 commented 2 years ago

@monsieurtanuki It's not working for me, I am on Flutter 3.0.3. What should I do?

P.s I really appreciate you getting back to me so quickly.

monsieurtanuki commented 2 years ago

@Zubi1001 I don't think it has anything to do with the flutter version, what we do in this package is very basic. So, you copied/pasted my code and it still does not work, am I right? As it works on my computer I cannot be really helpful. I suggest that you help us fix that bug by installing openfoodfacts-dart on your computer, trying to reproduce that bug and possibly printing the response body (which is not json formatted though it should).

M123-dev commented 2 years ago

Just tested it as well and I think I found the problem, when you plug in wrong credentials it fails as presumably the backend returns a error html page not a json.

@Zubi1001 can you check if your credentials are correct

We should catch this and throw a better error

Zubi1001 commented 2 years ago

@M123-dev Could my credentials be wrong if the login() function returns true?

Zubi1001 commented 2 years ago
"<!-- start templates/web/common/site_layout.tt.html -->

<!doctype html>
<html class="no-js" lang="en" data-serverdomain="openfoodfacts.net" dir="ltr">
<head>
    <meta charset="utf-8">
    <title>Error</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta property="fb:app_id" content="219331381518041">
    <meta property="og:type" content="food">
    <meta property="og:title" content="">
    <meta property="og:url" content="https://world.openfoodfacts.net">

    <meta property="og:image" content="https://world.openfoodfacts.org/images/misc/openfoodfacts-logo-en-356.png">
    <meta property="og:description" content="">
    <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon/favicon-16x16.png">
<link rel="manifest" href="/images/favicon/site.webmanifest">
<link rel="mask-icon" href="/images/favicon/safari-pinned-tab.svg" color="#5bbad5">
<link rel="shortcut icon" href="/images/favicon/favicon.ico">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-config" content="/images/favicon/browserconfig.xml">
<meta name="theme-color" content="#ffffff">

<meta name="apple-itunes-app" content="app-id=588797948">
<meta name="flattr:id" content="dw637l">

    <link rel="canonical" href="https://world.openfoodfacts.net">
    <link rel="stylesheet" href="https://static.openfoodfacts.net/css/dist/app-ltr.css?v=1658168089">
    <link rel="stylesheet" href="https://static.openfoodfacts.net/css/dist/jqueryui/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="https://static.openfoodfacts.net/css/dist/select2.min.css">
    <link rel="search" href="https://world.openfoodfacts.net/cgi/opensearch.pl" type="application/opensearchdescription+xml" title="Open Food Facts">

    <style media="all">

    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-HQX9SYHB2P&aip=1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('set', 'allow_google_signals', false);
  gtag('config', 'G-HQX9SYHB2P', {"anonymize_ip": true, 'allow_google_signals': false});
</script>
<!-- Matomo -->
<script>
  var _paq = window._paq = window._paq || [];
  /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
  _paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
  _paq.push(["setCookieDomain", "*.openfoodfacts.org"]);
  _paq.push(["setDomains", ["*.openfoodfacts.org"]]);
  _paq.push(["setDoNotTrack", true]);
  _paq.push(["disableCookies"]);
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//analytics.openfoodfacts.org/";
    _paq.push(['setTrackerUrl', u+'matomo.php']);
    _paq.push(['setSiteId', '5']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
  })();
</script>
<noscript><p><img src="//analytics.openfoodfacts.org/matomo.php?idsite=5&amp;rec=1" style="border:0;" alt="" /></p></noscript>
<!-- End Matomo Code -->

</head>
<body class="error_page">
<nav class="top-bar" data-topbar id="top-bar">
    <ul class="title-area">
        <li class="name">
            <h2><a href="/">
                <img id="logo" src="https://static.openfoodfacts.net/images/logos/off-logo-horizontal-light.svg" alt="Open Food Facts" style="height:2rem;">
            </a></h2>
        </li>
        <li class="toggle-topbar menu-icon">
            <a href="#"><span>Menu</span></a>
        </li>
    </ul>
    <section class="top-bar-section">
    <label for="select_country" style="display:none">Country</label>
    <ul class="country_language_selection">
            <li class="has-form has-dropdown" id="select_country_li">
                <select id="select_country" style="width:100%" data-placeholder="Country">
                    <option></option>
                </select>
            </li>

    </ul>
    <ul class="search_and_links">
      <li class="show-for-large-up">
        <form action="/cgi/search.pl">
          <div class="row collapse">
            <div class="small-8 columns">
              <input type="text" placeholder="Search for a product" name="search_terms" value="Olive+Oil">
              <input name="search_simple" value="1" type="hidden">
              <input name="action" value="process" type="hidden">
            </div>
            <div class="small-4 columns">
              <button type="submit" title="Search"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="icon" aria-hidden="true" focusable="false"><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/><path d="M0 0h24v24H0z" fill="none"/></svg></button>
            </div>
          </div>
        </form>
      </li>
      <li class="show-for-large-only"><a href="/cgi/search.pl" title="Advanced search"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" class="icon" aria-hidden="true" focusable="false"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg></a></li>
      <li class="show-for-xlarge-up"><a href="/c

This is part of the string that jsonDecode is failing to decode, could it be that I am not receiving a Json response?

Zubi1001 commented 2 years ago

@monsieurtanuki @M123-dev

M123-dev commented 2 years ago

Yes it's a html answer, that's a common flaw with the api when something wrong happens it answers with a html page because the website and the api are the same project.

I couldn't see the problem in the html you send, could you check if there is a full version.

Also no the login method is supposed to work but to test if maybe it's broken maybe try to login on world.openfoodfacts.org

monsieurtanuki commented 2 years ago

@M123-dev Could my credentials be wrong if the login() function returns true?

@Zubi1001 It could if you're login in PROD and searching in TEST. Again, what the hell are you doing in TEST?