Catching Only the Errors You Expect
Joan’s report takes its title from her settings file. Her Python function, report_title(), has
one handler, except json.JSONDecodeError:, for the error a stray comma causes. Every other
exception passes through.
The port follows the Python line by line, down to the call, with JSON.parse() built in. The title
line swaps the brackets for dot access, settings.report.title. Say it gets a typo, reprot,
standing in for any bug you didn’t plan for.
The except line becomes catch (err), which, much like except Exception as err, receives every
error. Watch out for naming the type in the header, as in catch (SyntaxError err): JavaScript
stops with SyntaxError: Unexpected identifier 'err' before anything runs, because the parentheses
take only a name.
So the type moves into the catch body, as an if statement around the message. A JSON parse error
is a SyntaxError too, thrown while the code runs. instanceof asks, like Python’s isinstance(),
whether err is that kind of error. For the stray comma, it is. Unlike isinstance(),
instanceof is an operator, not a function call. Here’s the port, typo and all: