javascripterror-handling

Inner Errors (exceptions) in JavaScript


Is there a preferred way to include inner exceptions when throwing exceptions in JavaScript?

I'm relatively new to JavaScript coming from a C# background. In C#, you can do the following:

try 
{
  // Do stuff
}
catch (Exception ex)
{
  throw new Exception("This is a more detailed message.", ex);
}

In the samples I've seen in JavaScript, I haven't been able to find how to catch an exception, add a new message, and re-throw the new exception while still passing the original exception.


Solution

  • You can throw any object you want:

    try {
        var x = 1/0; 
    }
    catch (e) {
        throw new MyException("There is no joy in Mudville", e);
    }
    
    function MyException(text, internal_exception) {
        this.text = text;
        this.internal_exception = internal_exception;
    }
    

    Then an error will be thrown of type MyException with properties text and internal_exception.