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

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Curious about the future of data-driven systems? Join our Data Engineering roundtable and learn how to build scalable data platforms.

Data Engineering: The industry has come a long way from organizing unstructured data to adopting today's modern data pipelines. See how.

Threat Detection: Learn core practices for managing security risks and vulnerabilities in your organization — don't regret those threats!

Managing API integrations: Assess your use case and needs — plus learn patterns for the design, build, and maintenance of your integrations.

Related

  • How to Access Remote Desktops Using Apache Guacamole
  • Why React Router 7 Is a Game-Changer for React Developers
  • Storybook: A Developer’s Secret Weapon
  • Ditch Your Local Setup: Develop Apps in the Cloud With Project IDX

Trending

  • MuleSoft: Best Practices on Batch Processing
  • Dust: Open-Source Actors for Java
  • Understanding the Differences Between Repository and Data Access Object (DAO)
  • AWS Redshift Data Sharing: Unlocking the Power of Collaborative Analytics
  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
7.8K 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

  • How to Access Remote Desktops Using Apache Guacamole
  • Why React Router 7 Is a Game-Changer for React Developers
  • Storybook: A Developer’s Secret Weapon
  • Ditch Your Local Setup: Develop Apps in the Cloud With Project IDX

Partner Resources


Comments

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: