Debugging PhoneGap applications using Xcode console

When I started to play whit PhoneGap, my greatest issue was: “how can I debug my code?”, I use often tools such FireBug and JavaScript debugger included in Internet Explorer 8 (which is the first good thing IE has to offers!) but write and test my code on iPhone simulator is completely different. Fortunately PhoneGap offers a way to access to Xcode console and print messages by choosing among three different levels: log, warn and error. In order to print a message, we have to use the debug object, which has scope window (it is a global object), in this way:

debug.log("my log message");
// or
debug.warn("my warning message");
// or
debug.error("my error message");

To open Xcode console you have to choose “Run -> Console” from the toolbar (or CMD+SHIFT+R) and after a “Build and Run” (CMD+Enter), you will see your message appear in the console.
Testing applications while developing using PhoneGap and Xcode, is an intense activity, because errors are not automatically notified (like in FireBug or similar), so it’s really important to make use of try/catch/finally blocks and logging calls:

catch (e) 
    debug.error("Error using mycommand: " + e.message);
    // do something smart here :^)

Finally, in order to avoid problems related to Xcode cache, I suggest to always clean the cache by running “Build -> Clean” from the toolbar (or CMD+SHIFT+K) before doing a new build and eventually remove the application folder under “/Users/{your-name}/Library/Application Support/iPhone Simulator/User/Applications/{app-number}”.

  • Nice tips.

    IMHO dealing with silently failing javascript errors are almost more trouble than learning Objective C.

    It’s unfortunate that wrapping blocks of Javascipt in try/catch is the only way to even get a friggin error message!!!!!

  • You are right Rich, use JavaScript and similar frameworks to develop iPhone apps is terrifying. I’m learning Objective-C and Cocoa and I have to admit that is not so difficult as I thought :^)

  • phi

    WARNING: debug object is deprecated, please use console object

  • Sg

    I keep up with debugging this way and I think it’s pretty simple:

    window.onerror = function(msg,url,ln){
    var o = {msg:msg,url:url,ln:ln};
    console.log(“ERROR: ” + JSON.stringify(o));
    /* Uncomment to stop error propagation
    return true;

  • Milton Rodríguez

    Hey SG, our solution looks simple, but you’ll ever see:
    [INFO] ERROR: {“msg”:”TypeError: ‘undefined’ is not a function”,”url”:”undefined”,”ln”:0}

    Do you see another thing ?