Quantcast
Channel: SwhistleSoft Blog » javascript
Viewing all articles
Browse latest Browse all 8

Simple Javascript Error Handler

$
0
0

Simple Javascript Error Handler

If you have ever wanted a simple error handler utility for javascript that outputs error s on screen in a reasonable manner, check out this little script.

var ErrorManager=(function(){
var _this={
    errors:[],
    addError:function(msg){
        this.errors.push(msg);
    },
    delError:function(msg){
        for(i=0;i<this.errors.length;i++){
            if(msg==this.errors[i]){
                this.errors.splice(i,1);
                return;
            }
        }
    },
    clearErrors:function(msg){
        this.errors=[];
    },
    getLength:function(){
        return this.errors.length ;
    },
    toString:function(){
        return 'ErrorManager';
    },
    render:function(){
        var html='';
        if(this.errors.length<=0){
            return;
        }
        html +='<ul>';
        for(i=0;i<this.errors.length;i++){
            html +='<li>'+this.errors[i]+'</li>';
        }
        html +='</ul>';
        if($('#error').length>0){
            $('#error').html(html);
            $('#error').show();
        }
    }
    };
    return _this;
})();

Useage: This simple script is easy to use and include like most javascript
and needs no initialization.

 

Example Rendering:

document.onreadystatechange=function(){
    if (document.readyState == "complete") {
        ErrorManager.render(); // optimally should be the last line in document ready
    }
}

 

Requirements:

 

The script requires that an element with the id attribute set as “error” and that the javascript file is included – . There are style requirements that should be set up either using the following styles or customized by the site.

#error{
    background:#ff5555;
    border:solid red 1px;
    display:none;
}
#error ul{
    margin:0px;
    padding:5px;
    list-style:none;
}

The final requirement is to add some errors via:

ErrorManager.addError ( "Some Object is not defined" ) ;

Script Errors

If you have script errors then the ErrorManager may fail to load properly due to the face that script processing may halt. If you have code prior to ErrorManager being rendered though, an option may be to wrap that code in a try/catch in order to catch any exceptions and output them into the ErrorManager.

Who Uses This Script

To date, I am currently the only user of this simple utility script. The reasons why someone may want to use this script is to notify users of specific types of user errors such as input validation and as an alternative to javascript alert mechanisms. Other uses may involve showing loading success/failure information in regards to specific operations such as asset loading requirements or the like.


Viewing all articles
Browse latest Browse all 8

Trending Articles