How to log exceptions in JavaScript

Viewed 78649

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.

9 Answers

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.

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;
}

I had a similar problem.

Using console.table(error); worked well for me. It displays information in a table, and also lets me expand/collapse to see more details.

I wrote a handy function for it


const logError = (e: any) => {
   if (console.error) console.error(e, e.stack);
   else console.log(e)
}

The modern best practice (as I understand it) is to log the error as a separate argument to console.error (or console.log, console.warn, etc...)

try {
  maybeThrows()
} catch (e) {
  console.error('it threw', e);
}

Trying out this approach in practice:

try {
  throw Error('err') // Error object
} catch (e) {
  console.error('it threw', e); // it threw Error: err
}

try {
  throw 'up' // not an error object
} catch (e) {
  console.error('it threw', e); // it threw up
}

I ran the above in Chrome, and Node v16. Note that node did not include a stack trace for throw 'up', but did for the proper error. Chrome included the stack for both.

Related