DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • 5 Layers of Prompt Injection Defense You Can Wire Into Any Node.js App
  • Boosting React.js Development Productivity With Google Code Assist
  • Why Angular Performance Problems Are Often Backend Problems

Trending

  • Persistent Memory for AI Agents Using LangChain's Deep Agents
  • 5 AI Security Incidents That Broke Things in Production (and What They Have in Common)
  • Alternative Structured Concurrency
  • Observability for Agents and Workflows: Tracing Prompts, Tool Calls, and Business Outcomes End-to-End
  1. DZone
  2. Coding
  3. JavaScript
  4. JavaScript: Wrap All Methods (functions) In A Class With An Error Handler.

JavaScript: Wrap All Methods (functions) In A Class With An Error Handler.

By 
Jason McDonald user avatar
Jason McDonald
·
Dec. 18, 09 · Code Snippet
Likes (0)
Comment
Save
Tweet
Share
8.3K Views

Join the DZone community and get the full member experience.

Join For Free
Example of a way to wrap all methods in a class with an error handler. Could stand more improvement.


/**
@Description: Takes in an exception or string and turns it into an Error object,
  then appends the caller name to the message.
@Returns: A new Error object or null.
*/
function wrapError (e, caller)
{
  if (null === e) { return null; }
  var ret = ( (typeof e) === (typeof "") ) ? new Error(e) : new Error(e.message);
  ret.stackTrace = e.stackTrace || [];
  ret.stackTrace.push(caller);
  return ret;
}

/**
@Description: Returns a method (function) wrapped in an error handler. Does not 
  affect the behavior of the underlying function. Does not affec the function 
  either, only returns the wrapped function, doesn't modify it directly.
  Usage: function foo() { throw new Error("bar"); }; foo = safeWrapMethod(foo, "foo");
@Param: fn The function pointer/object to wrap.
@Param: name A string containing the name of fn as you wish it to be displayed in the call stack.
@Return: The method/function fn wrapped in an error handler.
*/
function safeWrapMethod (fn, name)
{ 
  try
  {
    return function ()
    { /* Wrapper added by safeWrapMethod */
      try
      {
        return fn.apply(this, arguments);
      }
      catch (e)
      {
        throw wrapError(e, name);
      }
    };
  }
  catch (e)
  {
    throw wrapError(e, "ErrorHelpers.safeWrapMethod");
  }
}

/**
@Description: Wraps every method in an object with an error handler. Affects the 
  instance of the object, but does not alter the underlying behavior of the methods.
@Param: o The class instance (object) to wrap.
@Param: name A string containing the name of the class. Method names will show as 
  "name.methodName" in an error's stack trace.
*/
function safeWrapClass (o, name)
{
  for (var m in o)
  {
    if (typeof(o[m]) === "function")
    {
      o[m] = safeWrapMethod(o[m], name + "." + m);
    }
  }
}; safeWrapClass = safeWrapMethod(safeWrapClass, "ErrorHelpers.safeWrapClass");


// Example Usage
function Foo() { safeWrapClass(this, "Foo"); }; Foo = safeWrapMethod(Foo, "Foo.ctor");
Foo.prototype.a = function () { throw new Error("oh noes!"); };
Foo.prototype.b = function () { this.a(); }
Foo.prototype.c = function () { this.b(); }

try
{
  var f = new Foo();
  f.c();
}
catch (e)
{
  var msg = e.message;
  if (e.stackTrace) { msg += "\r\n\r\nstackTrace: " + e.stackTrace.join("\r\n\tat "); }
  alert(msg);
  /*
  oh noes!
  
  stackTrace: Foo.a
    at Foo.b
    at Foo.c
  */
}

JavaScript

Opinions expressed by DZone contributors are their own.

Related

  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • 5 Layers of Prompt Injection Defense You Can Wire Into Any Node.js App
  • Boosting React.js Development Productivity With Google Code Assist
  • Why Angular Performance Problems Are Often Backend Problems

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook