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
Please enter at least three characters to search
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Mastering React App Configuration With Webpack

Trending

  • The Perfection Trap: Rethinking Parkinson's Law for Modern Engineering Teams
  • ITBench, Part 1: Next-Gen Benchmarking for IT Automation Evaluation
  • Driving DevOps With Smart, Scalable Testing
  • How Kubernetes Cluster Sizing Affects Performance and Cost Efficiency in Cloud Deployments
  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.1K 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

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Mastering React App Configuration With Webpack

Partner Resources

×

Comments
Oops! Something Went Wrong

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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!