Google’s Closure Compiler Service API: Displaying Warnings and Errors

This penultimate part of the series offers a quick overview of the debugging capabilities that the Closure Compiler Service API provides for free. Activating the API’s debugger is as easy as assigning the values “warnings” and “errors” to its “output_info” parameter.

Using the new web service released by Google in the last few weeks, called Closure Compiler Service API, is a straightforward process that can be mastered with minor hassles. The service will let you optimize your JavaScript snippets by means of a set of intuitive parameters, which allow you to control certain aspects related to the compiler’s behavior. These include the level of optimization that will be applied to the source JavaScript code, the format in which the output will be returned to the client, and even what kind of information will be displayed on screen once the corresponding compiling process has been executed.

Of course, if you’ve already read the previous installments of this series, you probably have clear idea of how to perform some of the aforementioned tasks through the Closure Compiler Service API. In those tutorials I developed a few basic examples that showed, among other things, how to apply different optimization algorithms to a sample JavaScript file, and how to serve the compiled output first in “text/javascript” format, then in XML and finally in JSON.

It’s valid to stress, though, that the Closure Compiler Service API comes with many other handy features that also deserve a close analysis — such as its ability to debug target JavaScript code by echoing the errors and warnings that might occur during the compiling process. As with other facets of the API, the behavior of its built-in debugger can be controlled easily by direct manipulation of its “output_info” argument.

With that said, in this penultimate part of the series, I’m going to set up a few additional examples that will demonstrate how to display errors and warnings via the argument just mentioned. So start reading right now!

Playing with the “output_info” argument: returning compiled JavaScript code to the client

As I said at the beginning, the Closure Compiler Service API can return to the client different kinds of information, according to the values assigned to its “output_info” parameter. If no value is passed to this argument, the compiler simply will return by default the compiled JavaScript code. This is the expected behavior in most use cases. Nevertheless, it’s possible to instruct the API to display errors and warnings with the same ease.

But before I start demonstrating how to accomplish that (and for the sake of completeness), here’s an example that uses the aforementioned “output_info” argument in a standard fashion, as it sends back to the client only the optimized JavaScript code:     

<?php

// example using output_info = compiled_code
try {
 
    // include the autoloader class
    require_once ‘Autoloader.php’;
    Autoloader::getInstance();

    // create an instance of the file handler class and read the specified JavaScript file
    $fileHandler = new FileHandler;
    $js = $fileHandler->read();
   
    // build the array of arguments that will be passed to the closure compiler API
    $data = array(
         ‘js_code’ => $js,
         ‘compilation_level’ => ‘ADVANCED_OPTIMIZATIONS’,
         ‘output_format’ => ‘text’,
         ‘output_info’ => ‘compiled_code’
    );
   
    // create an instance of the ClosureCompilerHandler class
    $compilerHandler = new ClosureCompilerHandler($data);
    // query the closure compiler API and get the compiled JavaScript function
    $response = $compilerHandler->sendRequest();
    $compilerHandler->sendHeader(‘js’);
    // print to screen the compiled JavaScript function
    echo $response;
    /*
    displays the following
 
    var a=document.createElement("div");a.setAttribute("id","divid");a.setAttribute("class","divclass");document.getElementsByTagName("body")[0].appendChild(a);
    */  
}
catch (Exception $e) {
    echo $e->getMessage();
    exit();
}

As you can see above, the value assigned to the “output_info” parameter is the string “compiled_code,” which tells the compiler to do exactly that: return the compiled JavaScript, regardless of the level of optimization applied to it. While this is the default behavior of the compiler, since most of the time a client querying its API will expect to receive the optimized output for further processing, it’s feasible to return the warning and errors raised during the compiling process.

If you’re wondering how this can be done, the answer is simple: assigning the value “warnings” to the “output_info” parameter will cause the compiler to send to the client the corresponding warnings, while a value of “errors” will return only the potential errors. That’s not rocket science, is it?

If you’re interested in seeing the debugging capabilities of the Closure Compiler Service API in action, in the next section I’m going to build another example that will show how to make the API to display the warnings raised during the optimization process.

To see how this example will be developed, jump forward and keep reading.   

{mospagebreak title=Debugging with the Closure Compiler Service API}

In reality, making the Closure Compiler Service API send the warnings that occurred in the compiling phase is as simple as assigning the value “warnings” to its “output_info” argument. Of course, the best way to understand this process is by example, so below I created one which accomplishes this in a basic way. Pay close attention to it, please:

<?php

// example using output_info = warnings
try {
 
    // include the autoloader class
    require_once ‘Autoloader.php’;
    Autoloader::getInstance();

    // create an instance of the file handler class and read the specified JavaScript file
    $fileHandler = new FileHandler;
    $js = $fileHandler->read();
   
    // build the array of arguments that will be passed to the closure compiler API
    $data = array(
         ‘js_code’ => $js,
         ‘compilation_level’ => ‘ADVANCED_OPTIMIZATIONS’,
         ‘output_format’ => ‘text’,
         ‘output_info’ => ‘warnings’
    );
   
    // create an instance of the ClosureCompilerHandler class
    $compilerHandler = new ClosureCompilerHandler($data);
    // query the closure compiler API and get the compiled JavaScript function
    $response = $compilerHandler->sendRequest();
    $compilerHandler->sendHeader(‘js’);
    // print to screen the compiled JavaScript function
    echo $response;
}
catch (Exception $e) {
    echo $e->getMessage();
    exit();
}

See how easy it is to instruct the API to send the compiling warnings? I bet you do! If you test the previous example on your own browser, you won’t get any warnings, since the JavaScript function passed to the API has been coded correctly. If you’re feeling adventurous and want to see how warnings are returned to the client, I suggest you deliberately alter the function (yes, you can be as evil as you want) and observe what kind of response you receive from the compiler.

And now that you know how to make the Closure Compiler Service API return warnings instead of compiled JavaScript code, it’s time to explore its debugging capabilities, so that you can learn how to put them to work for you.

In the last segment of this article I’m going to build a final example that will show how to instruct the API to send you the errors generated during the optimization process.

To learn the full details of this example, read the following lines.

A final example: showing compilation errors

As I said before, it’s ridiculously easy to make the Closure Compiler Service API return to the client the errors raised after optimizing a supplied JavaScript snippet. In simple terms, the process is reduced to first assigning the value “errors” to the “output_info” option, and then catching the corresponding response.

To demonstrate how to debug JavaScript code via this parameter, below I deliberately introduced a syntax error in the sample “createDiv()” function used previously, which will make the compiler complain loud and clear.

Here’s the amended version of the function:

(function.js)

function createDiv(idAttr, classAttr) {
    // create the div
    var div = document.createElement(‘div’);
    // assign the ‘id’ attribute to the div element
    div.setAttribute(‘id’, idAttr);
    // assign the ‘class’ attribute to the div element
    div.setAttribute(‘class’, classAttr);
    append the div element to the document
    document.getElementsByTagName(‘body’)[0].appendChild(div);
};
// call the previous function
createDiv(‘divid’, ‘divclass’);

As you can see, the function now has a non-valid comment right before the statement that appends the div element to the DOM. At this point, if the corresponding JavaScript file is submitted to the compiler API through the following PHP script:

<?php

// example using output_info = errors
try {
 
    // include the autoloader class
    require_once ‘Autoloader.php’;
    Autoloader::getInstance();

    // create an instance of the file handler class and read the specified JavaScript file
    $fileHandler = new FileHandler;
    $js = $fileHandler->read();
   
    // build the array of arguments that will be passed to the closure compiler API
    $data = array(
         ‘js_code’ => $js,
         ‘compilation_level’ => ‘ADVANCED_OPTIMIZATIONS’,
         ‘output_format’ => ‘text’,
         ‘output_info’ => ‘errors’
    );
   
    // create an instance of the ClosureCompilerHandler class
    $compilerHandler = new ClosureCompilerHandler($data);
    // query the closure compiler API and get the compiled JavaScript function
    $response = $compilerHandler->sendRequest();
    $compilerHandler->sendHeader(‘js’);
    // print to screen the compiled JavaScript function
    echo $response;
}
catch (Exception $e) {
    echo $e->getMessage();
    exit();
}

then, the output returned to the client is not surprisingly a message containing the errors detected at compiling time:

Input_0:8: ERROR – Parse error. missing ; before statement
    append the div element to the document
               ^
Input_0:9: ERROR – Parse error. syntax error
    document.getElementsByTagName(‘body’)[0].appendChild(div);
              ^

Not too bad, huh? Most likely you’ll be utilizing your own JavaScript debugger before optimizing your snippets through the Closure Compiler Service API, but it’s always useful to test its built-in debugging capabilities, in case you need to make use of them in some particular situation. 

Final thoughts

In this penultimate episode of the series, I provided you with a quick overview of the debugging capabilities that the Closure Compiler Service API offers for free. As you just saw in the examples developed previously, activating the API’s debugger is as easy as assigning the values “warnings” and “errors” to its “output_info” parameter. It’s that simple, really.

In the last chapter, I’ll be exploring a few miscellaneous features included with the API, which permit you to return optimization statistics to the client, as well as to serve compiled code in a printer-friendly format.

Stick to my recommendation: don’t miss the last part!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan