0

When I run this code:

throw 'a string';

I get this stacktrace on my terminal:

$ node test.js

/home/user/test.js:2
throw 'a string';
^
a string

There is the filename and the line where this exception appeared.

I'm trying to build an exception logging mecanism and when I use the uncaughtException handler, I cannot get the filename nor the line.

process.on('uncaughtException', function() {
  console.log(arguments);
});

throw 'a string';

When I run this code I only get:

$ node test2.js

{ '0': 'a string' }

Is is possible to get the filename / line when I use the uncaughtException handler?

Thanks

soyuka
  • 8,839
  • 3
  • 39
  • 54
Unitech
  • 5,781
  • 5
  • 40
  • 47

2 Answers2

3

use throw new Error('my message');

C:\Users\xxx\Desktop>node test.js

C:\Users\xxx\Desktop\test.js:1 (function (exports, require, module, __filename, __dirname) { throw 'test'; ^ test

contents of test.js: throw 'test';

C:\Users\xxx\Desktop>node test2.js

C:\Users\xxx\Desktop\test2.js:1 (function (exports, require, module, __filename, __dirname) { throw new Error( ^ Error: test at Object. (C:\Users\xxx\Desktop\test2.js:1:69) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:906:3

contents of test2.js: throw new Error('test');

also:

In JavaScript, you can technically throw things that are not Errors, but this should be avoided. The result does not include the potential for getting a call stack, nor a "name" property for programmatic inspection, nor any useful properties describing what went wrong.

from Error Handling in Node.js

grabthefish
  • 962
  • 14
  • 30
0

You can't get a stack trace from a throwed string. In fact it's the Error object that builds the stack.

You might think of a workaround that would build a new Error when an exception is caught, but the stack trace won't go back to the throwed string.

Solution: never throw strings, use errors instead.

soyuka
  • 8,839
  • 3
  • 39
  • 54