Search code examples
autocompleteerror-handlingyuiyui3

How do I handle remote data source errors with YUI3 Autocomplete widget?


When using the YUI3 Autocomplete widget with a URL source which returns JSON data, is there a simple way to detect HTTP error responses?

Example:

Y.one('#ac-input').plug(Y.Plugin.AutoComplete, {
    resultHighlighter : 'phraseMatch',
    source : "http://example.com/api/item/search/?q={query}",
});

(For example, if the user hasn't authenticated on that server, the Autocomplete widget receives a 401 response and fails silently but logs the error to the console.)

I've searched but haven't found documentation specific to this issue - source diving didn't help, either. I think I'll have to roll my own datasource object so I can issue the request and detect the error.

Or is there a simpler way to pass an error event handler to the YUI3 Autocomplete widget for this type of data source?

Edit: See my follow-up answer for a simple solution using Y.on('io:failure').


Solution

  • A simple solution: use a global IO failure event handler. It works without the complexity of the DataSource.IO object as described in this answer.

    While I would rather handle the error locally in the AutoComplete widget event handlers, alas, I've not found a simple way to do that.

    Using Y.on('io:failure') event handling may be a much more direct approach if all you need to do is display info about comms errors.

    //
    // Handle IO failure event
    function ioFailureFunction(transaction, xhrObject) {
        errCode = xhrObject.status;
        // Insert the current error status into an HTML element...
        Y.one('#error').setContent(errCode);
    };
    Y.on('io:failure', ioFailureFunction);
    

    Rationale: I've found that using the DataSource.IO method outlined in this answer may introduce significant complexity, so if you have simple needs, this method is expedient and works with simple AutoComplete configurations -- thus you can keep your AutoComplete config simple and still handle IO errors...