小さなコンポーネントベースのJSフレームワークの例を使用したローカライズとエラー処理

物語は小さくなります-すべて具体的な例に。



したがって、必要なすべてのロジックを実装する基本クラス:



window.rwdk = ( function () {

// Private members.

var self = this ;

var _ = {};



// Private methods.

function run() {

_.run();

}



var handle_exception = function (e, component, method) {

var message, line;

component = component || 'Unknown' ;

method = method || 'Unknown' ;

if ( typeof e == 'string' ) {

message = e;

}

else if (e instanceof TypeError) {

line = e.lineNumber || 'undefined' ;

message = e.message;

}



alert( '[Component: ' + component + ', method: ' + method + ']'

+ '\n\n' + 'Error: ' + message

+ '\n\n' + 'Line: ' + line

);

}



//

// Public methods.

//



_.run = function () {}

/**

*

*/

_.wrap_public_methods = function (coll, component) {

var wrappedColl = {};

for ( var methodName in coll) {

if ( typeof coll[methodName] != 'function' ) {

continue ;

}

wrappedColl[methodName] = ( function (name) {

return function () {

var args = Array.slice(arguments, 0);

try {

coll[name].apply( this , args);

}

catch (e) {

handle_exception(e, component, name);

}

}

})(methodName);

}

return wrappedColl;

}



_.is_positive = function (x) {

return /^[1-9]\d*$/.test(x);

}



// Initialization.

if (!Array.slice) {

Array.slice = ( function (slice) {

return function ( object ) {

return slice.apply( object , slice.call(arguments, 1));

};

})(Array.prototype.slice);

}



window.onload = function () {

try {

run();

}

catch (e) {

handle_exception(e);

}

}

return _;

}

)();




* This source code was highlighted with Source Code Highlighter .






基本は ' wrap_public_methods 'メソッドです。このメソッドは、渡されたメソッドをラップし、それらで発生する例外をキャッチします。



コンポーネントの例:

function SomeComponent() {

var _self = this ;

var _ = {};



_.boo = function () {

throw 'some error has occured' ;

}



return rwdk.wrap_public_methods(_, 'SomeComponent' );

}




* This source code was highlighted with Source Code Highlighter .








使用例:

rwdk.run = function () {

var t = new SomeComponent();

// Issues exception.

t.boo();

}



* This source code was highlighted with Source Code Highlighter .








このアプローチの利点:コンポーネントレベルでのエラーのカプセル化とローカライズとその方法。



All Articles