Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  66] [ 1]  / answers: 1 / hits: 90207  / 15 Years ago, thu, august 6, 2009, 12:00:00

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 ConsoleApplication1Program.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.


More From » exception

 Answers
16

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.


[#98976] Monday, August 3, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristopher

Total Points: 58
Total Questions: 103
Total Answers: 102

Location: Netherlands
Member since Thu, Jul 1, 2021
3 Years ago
;