How to read a stack trace in Python and Node
Published
By the Unrust team · 10 min read · Editorial method
How to read a stack trace: error line first, then the first frame in your code. Python prints it last, JavaScript first. Re-run on 8 Python and 4 Node builds.
How do you read a stack trace? The short answer
To read a stack trace, start at the error: its type and message say what failed, and the nearest frame in your own code says where. Python prints the newest call last, so read it from the bottom up; JavaScript prints the newest call first, so read it from the top down.
A stack trace is what a runtime prints after a failure: the calls that were still active at that moment, each one a frame with a file and a line. Code tracing is a different skill, reading code by hand and following its values, and you use it to find out why a frame received a bad value.
The table compares the two formats; Python calls its version a traceback. We ran every program in this post on eight CPython builds (3.9.25 to 3.15.2) and four Node.js builds (18.20.4 to 24.11.0). The output shown comes from CPython 3.11.2 and Node.js 24.11.0, with our working folder printed as /app, and the text says where other builds differ.
Python (CPython) JavaScript (Node.js, V8)
-------------- ------------------------------------- -------------------------------------
Error line the last line the first line of err.stack
Call order oldest call first, newest last newest call first, oldest last
Start reading at the bottom, then go up at the top, then go down
Frame shape File "x.py", line 2, in name at name (x.js:2:21)
Not your code site-packages, the standard library node_modules, node:internal
Chained errors original first, final error last error first, original under [cause]
Frames kept all on 3.13+, newest 1000 on 3.9-3.12 the newest 10 (Error.stackTraceLimit)How do you read a Python traceback?
Read a Python traceback from the bottom up. The last line is the exception type and message, here KeyError: 'price', and each File line above it is one call, oldest first, so the frame directly above the error line is where Python raised it. Then find the first frame in your own file.
The program below totals a cart in which the second item has no price. load_cents fails on the lookup, and the traceback lists five calls, from <module> at the top to load_cents at the bottom.
The ^^^^ and ~~~~ marker lines come from CPython 3.11 and later: 3.9 and 3.10 print none, and 3.13 draws them differently. Ignore them at first, because the frames and the last line are the same on all eight builds.
Two details are easy to misread. The generator expression is its own frame, <genexpr>, which is why line 6 appears twice, and sum is missing because a built-in written in C adds no frame. A list comprehension shows up as <listcomp> on 3.9 to 3.11, but from 3.12 it adds no frame.
def load_cents(item):
return item["price"]["cents"]
def total(items):
return sum(load_cents(i) for i in items)
def checkout(cart):
return total(cart["items"])
cart = {"items": [{"name": "pen", "price": {"cents": 200}}, {"name": "ink"}]}
print(checkout(cart))
$ python3 cart.py
Traceback (most recent call last):
File "/app/cart.py", line 14, in <module>
print(checkout(cart))
^^^^^^^^^^^^^^
File "/app/cart.py", line 10, in checkout
return total(cart["items"])
^^^^^^^^^^^^^^^^^^^^
File "/app/cart.py", line 6, in total
return sum(load_cents(i) for i in items)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/cart.py", line 6, in <genexpr>
return sum(load_cents(i) for i in items)
^^^^^^^^^^^^^
File "/app/cart.py", line 2, in load_cents
return item["price"]["cents"]
~~~~^^^^^^^^^
KeyError: 'price'How do you read a JavaScript stack trace?
Read a JavaScript stack trace from the top down. The error line comes first, then one line per call that starts with at, newest first, each shown as name (file:line:column). Skip the built-in and Node.js frames, and start at the first frame whose path is in your project.
The same checkout as a Node.js program is below. The second item has no price, so item.price is undefined, and reading .cents from undefined throws a TypeError. The message names the property that was read, 'cents', not the one that was missing, 'price'.
Above the error line, Node prints the file and line, the source line and a caret, but only for an uncaught error. Below it, Array.map (<anonymous>) is a built-in and the node:internal lines are Node loading your file, so skip them; Object.<anonymous> is the top level of your own file, so read it.
This is the format of V8, the engine behind Node.js and Chrome, and V8's documentation warns that other engines format stacks differently. The node:internal lines change between Node versions, but the frames above them were identical on all four builds. In an ES module the paths are file:// URLs and the top-level frame has no function name.
function loadCents(item) {
return item.price.cents;
}
function total(items) {
return items.map(loadCents).reduce((sum, cents) => sum + cents, 0);
}
function checkout(cart) {
return total(cart.items);
}
const cart = { items: [{ name: 'pen', price: { cents: 200 } }, { name: 'ink' }] };
console.log(checkout(cart));
$ node cart.js
/app/cart.js:2
return item.price.cents;
^
TypeError: Cannot read properties of undefined (reading 'cents')
at loadCents (/app/cart.js:2:21)
at Array.map (<anonymous>)
at total (/app/cart.js:6:16)
at checkout (/app/cart.js:10:10)
at Object.<anonymous> (/app/cart.js:14:13)
at Module._compile (node:internal/modules/cjs/loader:1760:14)
at Object..js (node:internal/modules/cjs/loader:1893:10)
at Module.load (node:internal/modules/cjs/loader:1480:32)
at Module._load (node:internal/modules/cjs/loader:1299:12)
at TracingChannel.traceSync (node:diagnostics_channel:328:14)
Node.js v24.11.0How do the same frames line up in Python and JavaScript?
Both runtimes print the same five calls in opposite order. The loop is the one frame that looks different: Python lists the generator expression as <genexpr> and hides sum, while JavaScript lists the built-in as Array.map (<anonymous>). The error line moves with the order, last in Python and first in JavaScript.
The messages differ more than the frames. Python raised at the lookup and named the missing key, KeyError: 'price'. JavaScript returned undefined and failed one step later, so its message names the property read from undefined, 'cents', and you must work out that item.price was the undefined part.
So a frame shows where an error was raised, which is not always where the data went wrong. In both languages the next step is the same: open the first frame in your code, then look one frame up to see which call passed in the bad item.
Step Reading order Python (bottom to top) JavaScript (top to bottom)
---- -------------------------- ---------------------- ---------------------------
1 where it was raised load_cents, line 2 loadCents, line 2
2 the loop <genexpr>, line 6 Array.map (<anonymous>)
3 the function with the loop total, line 6 total, line 6
4 its caller checkout, line 10 checkout, line 10
5 where the program began <module>, line 14 Object.<anonymous>, line 14How do you find the line in your own code?
Walk from the error line toward the start of the program and stop at the first frame whose path is inside your project. While you look, skip the standard library, installed packages (site-packages in Python, node_modules in Node.js) and Node's own loader (node:internal). That frame is where you start reading, even when the error was raised deeper.
The program below passes None to json.loads. The last frame is inside the standard library, in json/__init__.py, and the error line says what it rejected: NoneType. The first frame in our own file is load_settings, line 7, so the question is why raw was None.
That None came from os.environ.get, which returns None when a variable is not set, and with APP_SETTINGS set to {} the same program runs. The library frame described the symptom, and our own frame held the cause one line above it.
import json
import os
def load_settings():
raw = os.environ.get("APP_SETTINGS")
return json.loads(raw)
settings = load_settings()
$ python3 startup.py
Traceback (most recent call last):
File "/app/startup.py", line 10, in <module>
settings = load_settings()
^^^^^^^^^^^^^^^
File "/app/startup.py", line 7, in load_settings
return json.loads(raw)
^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/__init__.py", line 339, in loads
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not NoneTypeWhat does "During handling of the above exception, another exception occurred" mean?
It means a second exception was raised while Python was handling the first, inside an except block. Python prints both tracebacks in the order they happened, so the first holds the original problem and the last, which ends the output, holds the exception that stopped the program. Read the final error line first, then scroll up to the first traceback.
In the program below, json.loads rejects single quotes, which JSON does not allow, and the except block raises a new ValueError. The first traceback ends at the JSONDecodeError, with one frame of ours, read_config line 6, and three from the standard library; the second ends at the ValueError raised on line 8.
With raise ... from err, Python swaps the separator for "The above exception was the direct cause of the following exception:" and the reading order stays the same. With raise ... from None the first traceback is hidden, and you see only the last one. We ran both forms on all eight builds.
The separator does not say who is at fault. When we put return fallback_port, an undefined name, inside the except block, Python printed the same separator and ended with a NameError, so the second traceback held the bug.
import json
def read_config(text):
try:
return json.loads(text)
except json.JSONDecodeError:
raise ValueError("config is not valid JSON")
read_config("{'debug': true}")
$ python3 config.py
Traceback (most recent call last):
File "/app/config.py", line 6, in read_config
return json.loads(text)
^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
^^^^^^^^^^^^^^^^^^^^^^
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/app/config.py", line 11, in <module>
read_config("{'debug': true}")
File "/app/config.py", line 8, in read_config
raise ValueError("config is not valid JSON")
ValueError: config is not valid JSONHow do you read an error with a [cause] in JavaScript?
Node prints the wrapper error first and the original under [cause], indented, with its own frames: the reverse of Python's order. The wrapper's frames show where the new error was thrown, and the cause shows what failed first. A line such as ... 6 lines matching cause stack trace ... folds frames both stacks share.
The program below is the JavaScript twin of the config example, using new Error(message, { cause }), which the Node.js documentation lists as added in v16.9.0. Node 22 and 24 word the cause as Expected property name or '}' in JSON at position 1 (line 1 column 2), and Node 18 words it Unexpected token ' in JSON at position 1.
Printing err.stack alone drops the cause: on all four builds the string held only the wrapper's frames, with no [cause] and no JSON.parse frame. Log the error object itself, with console.log(err) or util.inspect(err), to keep the whole chain.
function readConfig(text) {
try {
return JSON.parse(text);
} catch (err) {
throw new Error('config is not valid JSON', { cause: err });
}
}
readConfig("{'debug': true}");
$ node config.js
/app/config.js:5
throw new Error('config is not valid JSON', { cause: err });
^
Error: config is not valid JSON
at readConfig (/app/config.js:5:11)
at Object.<anonymous> (/app/config.js:9:1)
... 6 lines matching cause stack trace ...
at Module.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:154:5)
at node:internal/main/run_main_module:33:47 {
[cause]: SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
at JSON.parse (<anonymous>)
at readConfig (/app/config.js:3:17)
at Object.<anonymous> (/app/config.js:9:1)
at Module._compile (node:internal/modules/cjs/loader:1760:14)
at Object..js (node:internal/modules/cjs/loader:1893:10)
at Module.load (node:internal/modules/cjs/loader:1480:32)
at Module._load (node:internal/modules/cjs/loader:1299:12)
at TracingChannel.traceSync (node:diagnostics_channel:328:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:244:24)
at Module.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:154:5)
}
Node.js v24.11.0Why does a stack trace stop at 10 frames or skip async functions?
V8 keeps only the newest 10 frames by default, set by Error.stackTraceLimit, and it adds async frames only for await, Promise.all and Promise.any. A promise returned without await drops its callers from the trace: in the exercise below, the trace had one frame instead of four on all four Node.js builds.
The limit applies when the error is created, so raising it later does not lengthen an error that already exists. In the block below dive(14) calls dive 15 times, so a limit of 10 shows 10 dive frames and a limit of 40 shows all 15. To raise the limit without editing code, run node --stack-trace-limit=50 app.js.
Python collapses a repeated line, as in [Previous line repeated 996 more times], which we got on all eight builds from a recursion that hit the default recursion limit. With the recursion limit raised to 3,000 and a non-repeating recursion, CPython 3.9 to 3.12 printed only the newest 1000 entries and 3.13 to 3.15 printed all 3,000. Set sys.tracebacklimit to choose your own cap.
function dive(n) {
if (n === 0) return new Error('bottom reached');
return dive(n - 1);
}
function diveFrames(err) {
return err.stack.split('\n').filter((line) => line.includes('at dive')).length;
}
console.log('limit', Error.stackTraceLimit, '->', diveFrames(dive(14)), 'dive frames');
Error.stackTraceLimit = 40;
console.log('limit', Error.stackTraceLimit, '->', diveFrames(dive(14)), 'dive frames');
$ node limit.js
limit 10 -> 10 dive frames
limit 40 -> 15 dive framesPredict the frames: does return await change the trace?
Both loaders below call readUser, which waits one tick and then throws. One uses return await readUser(id) and the other uses return readUser(id).
Predict first: how many frames does each error.stack list, and which functions are named?
async function readUser(id) {
await Promise.resolve();
throw new Error('user ' + id + ' not found');
}
async function withAwait(id) {
return await readUser(id);
}
async function withoutAwait(id) {
return readUser(id);
}
async function show(label, load) {
try {
await load(7);
} catch (err) {
console.log('--- ' + label);
console.log(err.stack);
}
}
async function main() {
await show('return await readUser(id)', withAwait);
await show('return readUser(id)', withoutAwait);
}
main();Reveal the answer and explanation
With return await the stack lists four frames: readUser, async withAwait, async show and async main. Without it the stack lists one, readUser, and the callers are gone even though show still awaits the result. We got the same output on Node.js 18.20.4, 22.11.0, 22.23.5 and 24.11.0.
readUser paused at its first await, so by the time it throws, the call that started it has already returned and left the stack. V8's documentation says async frames are limited to await locations, Promise.all() and Promise.any(), and a bare return is none of them.
If readUser threw before its first await, its callers would still be on the stack and would be listed; we ran that too. The fix is return await inside withoutAwait, and the block shows both outputs.
$ node profile.js
--- return await readUser(id)
Error: user 7 not found
at readUser (/app/profile.js:3:9)
at async withAwait (/app/profile.js:7:10)
at async show (/app/profile.js:16:5)
at async main (/app/profile.js:24:3)
--- return readUser(id)
Error: user 7 not found
at readUser (/app/profile.js:3:9)Predict the top frame: Python max() or JavaScript reduce()?
Each program below asks for the best price in a cart that has no prices.
Predict first: which frame does JavaScript print at the very top, which frame does Python print last, and is either one yours?
# best.py
def best_price(prices):
return max(prices)
def report(cart):
return best_price(cart["prices"])
print(report({"prices": []}))
// best.js
function bestPrice(prices) {
return prices.reduce((a, b) => Math.max(a, b));
}
function report(cart) {
return bestPrice(cart.prices);
}
console.log(report({ prices: [] }));Reveal the answer and explanation
Python's last frame is best_price, line 2, which is our own code: max is a C built-in, so it adds no frame, and the error line, ValueError: max() arg is an empty sequence, says why. JavaScript's first frame is Array.reduce (<anonymous>), a built-in, and our code starts one line lower, at bestPrice.
So the top frame is not always yours. Skip the built-in, read bestPrice, then look one frame up: report passed cart.prices, and that array was empty. CPython 3.12 and later word the Python message as max() iterable argument is empty.
To keep an empty cart working, decide what it should return: max(prices, default=0) in Python, or an initial value, prices.reduce((a, b) => Math.max(a, b), 0), in JavaScript. Both return 0.
$ python3 best.py
Traceback (most recent call last):
File "/app/best.py", line 9, in <module>
print(report({"prices": []}))
^^^^^^^^^^^^^^^^^^^^^^
File "/app/best.py", line 6, in report
return best_price(cart["prices"])
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/best.py", line 2, in best_price
return max(prices)
^^^^^^^^^^^
ValueError: max() arg is an empty sequence
$ node best.js
/app/best.js:2
return prices.reduce((a, b) => Math.max(a, b));
^
TypeError: Reduce of empty array with no initial value
at Array.reduce (<anonymous>)
at bestPrice (/app/best.js:2:17)
at report (/app/best.js:6:10)
at Object.<anonymous> (/app/best.js:9:13)
at Module._compile (node:internal/modules/cjs/loader:1760:14)
at Object..js (node:internal/modules/cjs/loader:1893:10)
at Module.load (node:internal/modules/cjs/loader:1480:32)
at Module._load (node:internal/modules/cjs/loader:1299:12)
at TracingChannel.traceSync (node:diagnostics_channel:328:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:244:24)
Node.js v24.11.0How do you fix an error once you can read the trace?
Read the error line, open the first frame in your own code, and check the values on that line. Then look one frame up to see who passed them in, and fix the value where it first goes wrong, not at the line that raised the error. Do this before you paste the trace into an AI assistant.
The table runs the steps on the cart example. Step 2 is where print debugging helps: print(repr(item)) on the failing line shows {'name': 'ink'}, an item with no price. Our print debugging post explains how to predict the output first, so the print can prove you wrong.
Step Read Ask In the cart example
---- ---------------------------- ----------------------------- -----------------------------------
1 the error line what failed and what it names KeyError: 'price'
2 the first frame in your code which line and which values load_cents, line 2: {'name': 'ink'}
3 the frame above it who passed the value in total, line 6: loop over the items
4 the source of the value where the bad value began the second item in cartQuick answers about reading stack traces
Do you read a stack trace from the top or the bottom? It depends on the language. Python prints the newest call last, so you start at the bottom and read up; JavaScript in V8 prints the newest call first, so you start at the top and read down. In both, start at the error line and stop at the first frame in your own code.
What does a stack trace tell you? It tells you what failed (the error type and message), where it failed (the file, line and function of each frame) and which calls led there. It does not tell you why a value was wrong; for that, read the line, print the values and follow them one frame up.
What is the difference between a stack trace and a traceback? Mostly the name. Traceback is Python's word, and the Python tutorial describes the lines above the error as a stack traceback; JavaScript says stack trace, and its text lives in err.stack. The layout differs by language, but both list the calls that were active when the error occurred.
Can an AI assistant read a stack trace for you? It can explain one, but it sees only what you paste. Include the whole trace, the code of the first frame in your own code and the value that reached it. Read those yourself first, so you can check its answer against the frames instead of taking it on trust.
What does <anonymous> mean in a JavaScript stack trace? It marks a missing name or a missing source file. In Object.<anonymous> the function has no name; here it is the top level of your own file, so read it. In Array.map (<anonymous>) the built-in has no source file, so skip it and read the frames on both sides.
References and next steps
- Python documentation: Errors and exceptions (stack traceback, exception chaining)
- V8 documentation: Stack trace API (stackTraceLimit, async stack traces)
- Node.js documentation: Errors (error.stack, error.cause)
- Unrust blog: Print debugging: 7 ways your output lies
- Unrust blog: Python debugging exercises: 10 bugs to fix
- Unrust blog: Fix: list indices must be integers or slices
- Unrust blog: Separate the first symptom from the root cause in service logs
- How do you trace a bug across multiple files without an IDE?
See how you debug with AI off
Take Unrust's free diagnostic with the AI off: a quick warm-up, three short drills and a per-skill read, about 14 minutes in one sitting, with no account needed.
More from the blog
- Debugging interview: 6 steps and a mock round
Debugging & logs · 12 min read
- Print debugging: 7 ways your output lies
Debugging & logs · 9 min read
- Code review interview: a rubric and 4 diffs
Code review · 10 min read