Pull to refresh

Локализация и обработка ошибок на примере небольшого component-based JS-фреймворка

Reading time2 min
Views642
Сказ будет небольшим — все на конкретном примере.

Итак, базовый класс, реализующий всю необходимую логику:

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.


Преимущества подхода: инкапсуляция и локализация ошибок на уровне компонента и его метода.
Tags:
Hubs:
+4
Comments1

Articles