Introduction
We will go over How To Get Current Line Number In JavaScript.
I will break this review in the following sections:
- The problem of why you may need to get the line number in Javascript
- Show an example use-case of the problem
- Demonstrate a solution with a bonus tip to resolve the problem
I have been using this in many of my error reporting functions in Javascript.
I’m going to keep all the steps simple and straight to the point to avoid you have to spend endless hours debugging or trying to figure out why things aren’t working.
The Problem
The problem is to identify a way to get the line number of the Javascript error. Basically to do this you need to find a way programmatically in your error handling code to provide the failed line number that caused the issue. This could be a traceback handler or an exception try/catch code section. Lets take a look at this example below that could be problematic.
Example Of Problem
As an example code we will simply use something that tries to print out a variable that does not exist:
(async () => { let variable1 = 'test'; let variable2 = 'test11'; console.log('Starting to run code'); console.log(doesntexist); })();
In the code above we intentionally tried to print out a variable that’s not defined to cause an exception to happen. If you were to execute this you will get the following output:
$ yarn ts-node test.ts test.ts:7:17 - error TS2304: Cannot find name 'doesntexist'. 7 console.log(doesntexist);
This shows what we were expecting the ‘Cannot find name’ exception in Javascript. Let’s go over in the next section how to solve this.
Root Cause Of Problem
The root cause here is that by default when you try to print out information for an error you get Javascript will not catch the error for you neither show the line number that failed. In order to do this we need take a few extra steps which will be shown below.
Solution
Now lets move on to the solution which in this case is pretty simple.
To do this we basically have to handle the exception and print out the line number of the error object that we create in our handling code. To do this lets re-examine the code we went over earlier and see what happens.
(async () => { let variable1 = 'test'; let variable2 = 'test11'; console.log('Starting to run code'); try { console.log(doesntexist); } catch (err){ const terr = new Error(); console.log('Failed line number: ', terr.lineNumber); } })();
The code above when executed will basically show a print out with the line number that failed.
To Test our theory we will perform the steps mentioned above to verify that everything is good.
Test To See If it works
The process to do this is fairly simple. All you need to do is re-run your Javascript that had the problem. In this case if you have modified your exception handler that catches the error as shown above in our example you should be able to get the current line number in JavaScript from the Error object we created.
A further tip is to see the entire stack trace as well with the error on your code. In order to do this we can leverage here the console trace function which essentially gives us a series of function calls that were made that lead to the error. Besides getting the error number it’s good to know the order of how this was triggered and the answer is Tracing the print out to the originally caller.
This can be done simply by adding the following code in your try/catch block:
console.trace();
And the output would look something like this when executed:
[Log] Trace Console Evaluation (Console Evaluation 11:15) asyncFunctionResume Console Evaluation (Console Evaluation 11:3) Console Evaluation (Console Evaluation 11:17) evaluateWithScopeExtension (anonymous function) _wrapCall
In my case this was an anonymous function so there’s no top level root function that called it other than the Javascript interpreter running inside my Google Chrome browser or NodeJS depending on where you invoked it from.
Conclusion
We were able to successfully show How To Get Current Line Number In JavaScript.
If you found this useful and you think it may have helped you please drop me a cheer below I would appreciate it.
If you have any questions, comments please post them below or send me a note on my twitter. I check periodically and try to answer them in the priority they come in. Also if you have any corrections please do let me know and I’ll update the article with new updates or mistakes I did.
Do you use custome exception handling in your Javascript code?
I always have my custom error function as I like to tune in how much information it provides to me so I can better debug my application. I also like to add coloring to it to make the output a bit more readable. If you’d like to learn how I do this drop me a line below or on twitter and I’ll make a post about it.
If you would like to learn more about Node and Typescript please check the related articles below:
- Fix Cannot Find Namespace NodeJS
- Find Names In Text Using JavaScript
- Recharts Complete Guide With Examples
You can find some references below: