In this video, you followed the error that checkRun() throws as it climbed out of one function after another, and you moved the catch to the level of Ruth’s season log that can do something about a bad run.
Key Points
- One bad run still stops the whole import. Ruth moves the loop that calls
checkRun()out ofloadRuns(), so the import has its own step, where a bad run could be skipped. Her newimportRuns()inload.jsloops over the runs, checks each one withcheckRun(), and keeps it.main.jssends the runs throughimportRuns()before printing them. Grace Kim’s run innew-runs.jsonhas no distance, socheckRun()throws aTypeError. Nothing catches it, so the whole program stops, and even the good runs from Priya and Kwame never print. - Each call puts a frame on the call stack. When a function throws and there’s no
tryaround that line, the function stops there, its frame comes off, and the error comes out at the line that called it. The error keeps climbing, one frame at a time, until acatchstops it. If nothing does, the program stops and Node prints the report. - The
atlines in the report, read from the top, are the function that created the error, then the calls waiting under it.checkRun()creates its error right where it throws it, so here they also trace the error’s climb. - Catching the error inside
checkRun()with acatchthat logs and returns hides it. The message prints, but the call returns as it does for a good run, soimportRuns()keeps Grace’s run, and the season log printsundefined km. - Watch out for a function that logs a problem and carries on, with a
catchlike that one, or with a log where athrowshould be. The code that could respond never hears about it. - The code that can skip a run is the loop in
importRuns(). A smalltrythere holds the check and the push. WhencheckRun()throws, the error climbs one frame to the call inside thattry. Thecatchchecks the error’s name. It doesn’t useinstanceof, because a bug passesinstanceof Errortoo, so that check can’t pick out the date guard’s plainError. For the three typescheckRun()throws, it reports the run, the push is skipped, and the loop moves on. Anything else is a bug, sothrow error;sends it on. - That check has a limit. A bug that throws one of those three types would still be skipped as a bad run. Error types of your own, later on the path, tell the two apart.
- So throw where the problem is found, in
checkRun(). Catch where the code can respond, in the loop that can report the run and skip it. A function that can’t respond has nocatch, and the error climbs past it.
Final Code
This is check.js, unchanged from the last lesson, which throws for a bad run: