views:

345

answers:

4

As a C# developer I'm used to the following style of exception handling:

try
{
    throw SomeException("hahahaha!");
}
catch (Exception ex)
{
    Log(ex.ToString());
}

Output
------

SomeNamespace.SomeException: hahahaha!
    at ConsoleApplication1.Main() in ConsoleApplication1\Program.cs:line 27

Its really simple, and yet tells me everything I need to know about what the exception was and where it was.

How do I achieve the equivalent thing in JavaScript where the exception object itself might just be a string. I really want to be able to know the exact line of code where the exception happened, however the following code doesn't log anything useful at all:

try
{
    var WshShell = new ActiveXObject("WScript.Shell");
    return WshShell.RegRead("HKEY_LOCAL_MACHINE\\Some\\Invalid\\Location");
}
catch (ex)
{
    Log("Caught exception: " + ex);
}

Output
------

Caught exception: [object Error]

EDIT (again): Just to clarify, this is for internal application that makes heavy use of JavaScript. I'm after a way of extracting useful information from JavaScript errors that may be caught in the production system - I already have a logging mechanism, just want a way of getting a sensible string to log.

A: 

It is almost identical, see the manual: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Exception_Handling_Statements/try...catch_Statement

David Dorward
I'm really interested in knowing how to extact useful information from the exception - I've rephrased my question.
Kragen
A: 

You can use logging tools like Yahoo! UI Library - Logger to log the errors/informative messages.

Kirtan
+1  A: 

You can use almost in the same manner ie.

try
{
    throw new Error("hahahaha!");
}
catch (e)
{
    alert(e.message)
}

But if you want to get line number and filename where error is thrown i suppose there is no crossbrowser solution. Message and name are the only standart properties of Error object. In mozilla you have also lineNumber and fileName properties.

Eldar Djafarov
+1  A: 

I'm not sure whether or not it is cross browser or if it's what you are looking for, but I suggest you try:

window.onerror = function (err, file, line) {
    logError('The following error occurred: ' + 
    err + '\nIn file: ' + file + '\nOn line: ' + line);
    return true;
}
Nubsis