javascript自定义异常类要做到什么?
一,要有清晰的错误号用于识别异常的类别
二,以不同的形式输出异常信息
三,针对不同的异常要有个性化抛出
四,异常的字段只读
好咯,我们来实现一个这样的异常类:
var e_list = {}; var createExceptionGTX = function( code,info ){ e_list[code] = info; }; var ExceptionGTX = function( code,info ){ this.code = function(){return code;}; this.info = function(){ return info + '@' +e_list[code]; }; this.alert = function(){ alert(info + '@' +e_list[code]); }; this.console = function(){ console.log(info + '@' +e_list[code]); }; };
我们来实现以下这个异常的威力吧:
//定义一个非人类的异常 createExceptionGTX( '1000','非人类' ); var Human = function( country ){ if( 'riben' == country){ throw new Exceptioin('1000','riben'); } }; var hum; try{ hum = new Human('riben'); }catch(e){ e.alert(); }
如果这篇文章不点赞,你就被throw咯