The volunteer’s donations.py opens with the import’s own exception classes, before it reads a single row. Every other part of the script raises them or catches them, so they’re the first thing to move into the website’s JavaScript project.
With the classes right, the report can tell Joan which rows to fix, like line 3 (D-108), before anything goes into the books. In this lesson, you’ll port the three classes and the except clauses that tell them apart.
Port the Exception Hierarchy
Here’s how the Python script defines a base class for anything that stops an import and two subclasses:
class DonationError(Exception):
"""Anything that stops a donations import."""
class ExportMissingError(DonationError):
pass
class BadRowError(DonationError):
def __init__(self, line, donor, reason):
super().__init__(f"line {line} ({donor}): {reason}")
self.line = line
self.donor = donor
BadRowError builds its message from the line number, the donor, and the reason, and it keeps the line and the donor as attributes. That way, the report can point Joan at the exact row in her export.
Almost all of this carries over. In JavaScript, an instance of a class that extends the built-in Error is an error like any other. You can throw it, catch it, and read its .message. Here’s the port:
class DonationError extends Error {}
class ExportMissingError extends DonationError {}
class BadRowError extends DonationError {
constructor(line, donor, reason) {
super(`line ${line} (${donor}): ${reason}`);
this.line = line;
this.donor = donor;
}
}
const err = new BadRowError(
3,
"D-108",
"amount is not a number",
);
console.log(err.message);
console.log(err.line, err.donor);
console.log(err instanceof DonationError, err instanceof Error);
The last three lines check the bad row from line 3 of november.csv:
line 3 (D-108): amount is not a number
3 D-108
true true
The two empty classes show the first difference. Python needs something in a class body, which is why DonationError has its docstring and ExportMissingError has pass. JavaScript marks the body with braces, so an empty pair, {}, is a complete class body.
A class with no constructor passes its arguments up to the class above it, as in Python. So new ExportMissingError("no export at december.csv") hands the text to Error, which stores it as .message.
BadRowError defines its own constructor, and it follows the same order as Python’s __init__(). It calls super() with the finished message first and then sets its two properties. Here the order is required because JavaScript doesn’t let a subclass’s constructor use this before super() has run.
The last output line shows what keeps the hierarchy useful. instanceof is true for an error’s own class and every class above it, so a BadRowError is also a DonationError and an Error, as isinstance() would say in Python.
Catch the Most Specific Class First
With the classes in place, the script’s main() can tell its failures apart. The real read_export() opens the file, but a stand-in that always fails is enough to test the exception handling. Here it is in Python, with separate except clauses for BadRowError and DonationError:
import sys
def read_export(path):
raise ExportMissingError(f"no export at {path}")
try:
read_export("december.csv")
except BadRowError as err:
print(f"Nothing imported: check line {err.line}")
except DonationError as err:
print(f"Nothing imported: {err}", file=sys.stderr)
Python prints Nothing imported: no export at december.csv to standard error. The missing export isn’t a BadRowError, so the second clause catches it.
JavaScript has no typed catch clauses. One catch (err) block receives every error, so the clauses become an if/else if chain of instanceof checks. The block repeats the classes so it runs on its own, and adds readExport():
class DonationError extends Error {}
class ExportMissingError extends DonationError {}
class BadRowError extends DonationError {
constructor(line, donor, reason) {
super(`line ${line} (${donor}): ${reason}`);
this.line = line;
this.donor = donor;
}
}
function readExport(path) {
throw new ExportMissingError(`no export at ${path}`);
}
try {
readExport("december.csv");
} catch (err) {
if (err instanceof BadRowError) {
console.log(`Nothing imported: check line ${err.line}`);
} else if (err instanceof DonationError) {
console.error(`Nothing imported: ${err.message}`);
} else {
throw err;
}
}
The port prints the same line as Python, to standard error through console.error():
Nothing imported: no export at december.csv
The last branch does what Python does for free. An error that no except clause matches keeps going up in Python, but JavaScript’s catch has already caught it, so throw err sends anything that isn’t a donations error on its way. Without it, a typo in your own code would vanish silently.
The order of the branches matters, as the order of except clauses does. Watch out for putting the DonationError check first. Every BadRowError is also a DonationError, so the base class’s branch would catch it, and the err.line branch would never run.
The second branch reads err.message rather than putting err itself in the template literal. Watch out when you port Python’s f"{err}". ${err} or String(err) turns an error with a message into its name, a colon, and its message, so the line would read Nothing imported: Error: no export at december.csv. The next lesson explains why it says Error.
So in a JavaScript program, you define one base class that extends Error, derive every other error class from it, and set extra properties after super(). A single catch then checks instanceof from the most specific class down to the base and rethrows the rest.
The report has one more line to port, the one that names the class of the error that stopped the import, as Python’s type(err).__name__ does. In the next lesson, Naming Your Error Classes, you’ll port that line with err.name and find out where JavaScript gets an error’s name from.