• 周六. 5月 18th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Implement Client-side Bug Reporting with UserSnap

[db:作者]

2月 14, 2023

Imagine the following scenario: your clients visit the website (let’s imagine this one) and see anything but the expected result. The normal reaction is to call you (at the most inappropriate time) and ask you to fix it ASAP, because they’re losing money.

How can we help the user report the bug as accurately as possible?

The bug

Let’s have a really simple JSON request and an error to be able to reproduce our case:

$json_data = '{"value":1,"apples":2,"name":3,"oranges":4,"last one":5}';

//we will simulate the json data, but imagine that this is the normal data exchanged daily between your client’s website and a 3rd party API

$ch = curl_init('http://talkweb.eu/labs/fr/json_callback.php');                                                                 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);                                  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                'Content-Type: application/json',                      
        'Content-Length: ' . strlen($json_data)));
                                                                                                             
//the normal CURL request, nothing strange here:
$result = curl_exec($ch);

//receiving the data back
$f_data =  json_decode($result,true);

//showing a greeting with the output
echo  “Welcome”. $f_data['username'];

If you visit the test website now, you will notice that there’s a problem.

The question is – how can the client report it faster with all the data you need to fight the bug:

  • Json data,
  • Server-side Javascript and XmlHttpsRequest errors,
  • Some core PHP errors
  • …and meta data.

An interesting solution for gathering this information is UserSnap. A widget that lets your users mark up a screenshot of the site they’re on and send you everything that’s in the JavaScript console. PHP errors don’t end up there, though, do they? Let’s make them. First, we’ll gather the server side errors.

Gathering Errors

Let’s add some more code to the example in order to see how we can collect the data we need. Introducing a really simple class to help us:

<?
class SendToUsersnap
{
    var $m;
    //Save all logs in an array. You can use an even more elegant approach but right now I need it to be simple for the sake of this tutorial.
    function log ( $data, $type ) {
    
        if( is_array( $data ) || is_object( $data ) ) {
            $this->m[]= "console.".$type."('PHP: ".json_encode($data)."');";
        } else {
            $this->m[] = "console.".$type."('PHP: ".$data."');";
        }
    }
  // Print all logs that have been set from the previous function. Let’s keep it simple.
    function  out (){
         for ($i=0;$i<count($this->m);$i++)
          {
              echo $this->m[$i]."\n";
          }
        
        
        }
}

Now let’s use this class to record all errors and logs we may need.

require_once('Usersnap.class.php'); 
    $s = new SendToUsersnap;

    $json_data = '{"value":1,"apples":2,"name":3,"oranges":4,"last one":5}';
    $s->log('Initializing the JSON request',"info");
    $s->log($json_data,"log");
 
    $ch = curl_init('http://talkweb.eu/labs/fr/json_callback.php');             
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);                           
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                         
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                 
        'Content-Type: application/json',                           
        'Content-Length: ' . strlen($json_data)));                                                                                                                   
 
    $result = curl_exec($ch);
    $f_data =  json_decode($result,true);
    
    echo  'Welcome'. $f_data['usersname'];
    
    $s->log($f_data,"log");
    $s->log(error_get_last(),"error");

Pass it to UserSnap

Let’s add the UserSnap code snippet at the end of our page and see what happens. (You may need an account to use this widget. Usersnap offers free licenses for Open Source projects and a free testing period for commercial ones.

<script type="text/javascript">
  (function() {
  var s = document.createElement("script");
    s.type = "text/javascript";
    s.async = true;
    s.src = '//api.usersnap.com/load/'+
            'your-api-key-here.js';
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
  })();

 var _usersnapconfig = {
   loadHandler: function() {
        <?php
    //just print all errors collected from the buffer.
 $s->out(); ?>
     }
 };
</script>

Note: You would do this in a view template in a real framework, but as we’re not using a real MVC app here, we’re skipping that part.

The user will see a “report bug” button on the page and will write you a message like “it’s not working, fix it asap”. Generally, this would be useless information, but this time, we get this gorgeous error log attached, too:

Now you can see that there is initialization in place:

$s->log('Initializing the JSON request',"info");

You can see the data we will send – the same as usual

$s->log($json_data,"log");

And you can see the output. Yes, the problem is there. Obviously there is an auth problem.

$s->log($f_data,"log");

You can get even the core PHP errors to help you with the debugging.

$s->log(error_get_last(),"error");

Your client will only have to click the button once and you will get everything you need to fight the bug faster:

  1. Errors and Logs (as shown above)
  2. Annotated screenshot – if the problem is more complex than this simple example
  3. Screen size, Browser version, OS and the plugins installed in the browser

Of course you can turn this feature on only when your client needs it. To limit the availability of the widget, add an IP filter or a query param barrier, open a dev.* subdomain, etc.

Conclusion

This is not a script-monitoring tool and will not deliver information automatically when and if the problem appears. This approach will work only if an user or a client reports a bug and you as a developer or QA need more info on how to fight the bug. Imagine it as a remote debugger, but for client-side errors + events and data you send from PHP to JavaScript.

I’d love to answer all of your questions! Leave your feedback below!

Share This Article

Bogomil Shopov – Bogo

Bogomil is a geek addicted to the Internet and its power. Before he was mentioned in Wikileaks and Forbes (twice) he was a nice person. He loves beers, traveling and his family a lot. Monty Python and Metal music fan.

    BrunoSdebugdebuggingerrorerrorsjsPHPusersnap

    const t=”undefined”!=typeof HTMLImageElement&&”loading”in HTMLImageElement.prototype;if(t){const t=document.querySelectorAll(“img[data-main-image]”);for(let e of t){e.dataset.src&&(e.setAttribute(“src”,e.dataset.src),e.removeAttribute(“data-src”)),e.dataset.srcset&&(e.setAttribute(“srcset”,e.dataset.srcset),e.removeAttribute(“data-srcset”));const t=e.parentNode.querySelectorAll(“source[data-srcset]”);for(let e of t)e.setAttribute(“srcset”,e.dataset.srcset),e.removeAttribute(“data-srcset”);e.complete&&(e.style.opacity=1)}}

    Up Next

    A Side-by-Side Comparison of AWS, Google Cloud and AzureLucero del Alba
    A Side-by-side Comparison of Express, Koa and Hapi.jsOlayinka Omole
    Crash Reporting an Android App with Crashlytics and FabricTheodhor Pandeli
    Logging Errors in Client-Side ApplicationsLukas White
    Client-Side Form Validation with HTML5Collins Agbonghama
    Design a Multi-​​Page Form in WordPress: Form Completion and Data ReportingJustyn Hornor

    /**//**/

    [db:作者]

    相关文章

    Ubuntu下安装nginx
    nginx 配置用户认证
    windows环境下安装nginx

    发表回复

    您的电子邮箱地址不会被公开。 必填项已用*标注

    You missed