Search code examples
javascriptexceptionevent-bubblingthrow

JavaScript Exception/Error Handling Not Working


This might be a little hard to follow.

I've got a function inside an object:

f_openFRHandler:    function(input) {
            console.debug('f_openFRHandler');
            try{
                //throw 'foo';
                DragDrop.FileChanged(input);
                //foxyface.window.close();
            }
            catch(e){
                console.error(e);
                jQuery('#foxyface_open_errors').append('<div>Max local storage limit reached, unable to store new images in your browser. Please remove some images and try again.</div>');
            }
        },

inside the try block it calls:

this.FileChanged = function(input) {
            // FileUploadManager.addFileInput(input);
            console.debug(input);
            var files = input.files;
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                if (!file.type.match(/image.*/)) continue;

                var reader = new FileReader();
                reader.onload = (function(f, isLast) {
                    return function(e) {
                        if (files.length == 1) {
                            LocalStorageManager.addImage(f.name, e.target.result, false, true);
                            LocalStorageManager.loadCurrentImage();
                            //foxyface.window.close();
                        }
                        else {
                            FileUploadManager.addFileData(f, e.target.result); // add multiple files to list
                            if (isLast) setTimeout(function() { LocalStorageManager.loadCurrentImage() },100);
                        }
                    };
                })(file, i == files.length - 1);
                reader.readAsDataURL(file);
            }
            return true;

LocalStorageManager.addImage calls:

this.setItem = function(data){
                localStorage.setItem('ImageStore', $.json_encode(data));
        }

localStorage.setItem throws an error if too much local storage has been used. I want to catch that error in f_openFRHandler (first code sample), but it's being sent to the error console instead of the catch block. I tried the following code in my Firebug console to make sure I'm not crazy and it works as expected despite many levels of function nesting:

try{
    (function(){
        (function(){
            throw 'foo'
        })()
    })()
}
catch(e){
    console.debug(e)
}

Any ideas?


Solution

  • var reader = new FileReader();
                    reader.onload = (function(f, isLast) {
    

    Likely that's your problem right there - the FileReader probably calls onload asynchronously, at a time when your try/catch is no longer in scope. There may be a separate error handler function available on the FileReader interface, or you might need to move the try/catch into the anonymous function you're passing to onread().