cancel
Showing results for 
Search instead for 
Did you mean: 

Exception handling good practice in Jscript

Highlighted
Community Leader

Exception handling good practice in Jscript

Hi all,

 

I recently posted a question regarding how to capture the call stack so I can output it to the log when something goes wrong.  What I did discover though is that that's not actually what I should have been asking Smiley Tongue

 

If you are interested:

 

Previous question

 

Now on to the current question.  What is the best way to do robust error handling of try..catch.. using Jscript.  I have an OO background (c#) so naturally tend to go down that route when trying to solve an issue.  That isn't always the right solution for scripting languages though.  From the previous post:

 

function Scriptcall1()
{
  try
  {
    LogErrorStack1();
  }
  catch(e)
  {
   switch(e)
   {
    case "1":
    Log.Message("This isn't serious, just continue");
    break;
    case "2":
    Log.Error("This is very serious");
    break;
   }
  }
}

function Scriptcall2()
{
  try
  {
    LogErrorStack1();
  }
  catch(e)
  {
   switch(e)
   {
    case "1":
    Log.Error("This is very serious this time");
    break;
    case "2":
    Log.Message("This isn't serious this time");
    break;
   }
  }
}

function LogErrorStack1()
{
  try   
  {
    LogErrorStack2();
  }
  catch(e)
  {
    throw e;
  }
}

function LogErrorStack2()
{
  try
  {
    throw("1");
    // or throw("2");
  }
  catch(e)
  {
//***** Here is the actual question I should be asking: ********
    LogException(e,"Perhaps you should try that again"); //But I don't want this to error. I  want to re-throw the exception to the top level function and let that decide if it's a serious problem
    throw e;
  }
}

As you can see, my outlook is to equivalently re-throw an exception up the chain until it reaches a function that knows what to do with it and whether to catch and throw or catch and continue.

Case "1"; Case "2" isn't ideal either, since it leaves an opening for a new "Exception" type to be added down the road that is then not handled.  How do you handle this ?  One of the ideas I'm thinking of is to build a custom exception "class" which is just a KVP with Exception Types which I define in an enum as key and call stack as value.  Can you throw this ?  I'm all ears to hear what you think of my attempts.


-------------------------------------------------
Standard syntax disclaimers apply
Regards,
1 REPLY 1
Community Hero

Re: Exception handling good practice in Jscript

@tristaanogre Any ideas?

February News
Top Kudoed Authors