Loading video player…

Naming Your Error Classes

Naming Your Error Classes

Joan’s December export doesn’t exist yet, so the Python import stops before it reads a row. Its report names the problem before the message, which tells Joan to export December, not to fix rows. Python takes that name from the error’s class:

Language: Python
    except* DonationError as group:
        for err in group.exceptions:
            name = type(err).__name__
            print(f"Nothing imported ({name}): {err}",
                  file=sys.stderr)

It prints Nothing imported (ExportMissingError): no export at december.csv. Its second line, the cause, is the next section’s.

In the JavaScript port, the classes extend each other as in Python, and main()’s catch finds the DonationError branch with instanceof. The catch gets the one error, so there’s no loop. Every JavaScript error has a name property, and a built-in RangeError’s name is "RangeError", so type(err).__name__ becomes err.name. The message is err.message, since Python’s f"{err}" is only the message:

Language: JavaScript
    } else if (err instanceof DonationError) {
      const name = err.name;
      console.error(
        `Nothing imported (${name}): ${err.message}`,
      );

Run it, and nothing crashes, the message is right and the exit code is 1, as in Python. But the name is wrong:

Language: Shell
$ node donations.js december.csv
Nothing imported (Error): no export at december.csv

JavaScript does know the class: the instanceof check matched it as a DonationError, and err.constructor.name is "ExportMissingError". But name isn’t the class’s name. It’s a property, and when the error doesn’t hold one, JavaScript falls back to the object its class shares with every instance, its prototype, then the class above’s, then Error.prototype, the object every error shares, where name is "Error".

A built-in RangeError’s prototype sets its own name, so its lookup stops there.

It’s like a Python instance falling back to class attributes, except JavaScript keeps them on the prototype, a separate object, not on the class. As in Python, the class’s name isn’t on that path: you ask the class for it, with type(err).__name__ there and err.constructor.name here. Prototypes get a course of their own later.

Node’s own crash output reads the class: an uncaught BadRowError still prints BadRowError: line 3 (D-108): amount is not a number, with line: 3 and donor: 'D-108' after the stack, and console.error(err) does the same. But ${err} and your report both say Error, so a test crash won’t show you the slip.

Your report could print err.constructor.name instead, but the fix belongs where the error is made, in the base class, once. Its constructor takes a message and options, passes both up to super() unchanged (the next section is what the options are for), and sets this.name from new.target.name:

Language: JavaScript
class DonationError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = new.target.name;
  }
}

class ExportMissingError extends DonationError {}

Inside a constructor, new.target is the class that new was called on, like type(self) in a Python __init__, so for a new ExportMissingError it’s ExportMissingError, even though the constructor belongs to DonationError. A class with no constructor of its own gets one that passes its arguments up. BadRowError’s own constructor calls super(), and its name is "BadRowError". The report now matches the Python’s line:

Language: Shell
$ node donations.js december.csv
Nothing imported (ExportMissingError): no export at december.csv

The error as text, ${err}, started with Error in the last lesson’s note; now it starts with ExportMissingError. Python’s f"{err}" is still only the message, so err.message stays in the report.

A JavaScript developer names every class once, in the program’s base class, so any error class you add later names itself. You’ll also see name = "BadRowError"; set by hand in each class, as a field: it works, but it has to be kept in step with the class name.

Next up is Report Each Rejected Pledge: on the food bank website’s pledge form, you’ll report each rejected pledge with its problem’s name and message, as the Python version does.

00:00 Joan’s December export doesn’t exist yet. Run the Python import on it, and the report names the problem, ExportMissingError, before the message.

00:11 That name tells Joan to export December, not to fix rows. Python takes it from the error’s class, with type(err).__name__, in the report. The second line, the cause, gets its own section next.

00:27 Here, you port the first line to JavaScript, name and all. In main()’s catch, the DonationError branch is an instanceof check.

00:38 The catch gets the one error, so there’s no loop. Every JavaScript error has a name property, and a built-in RangeError’s name is its class’s name.

00:49 So type(err).__name__ becomes err.name in the port. print() becomes console.error(), and the f-string a template literal, with err.message, since Python’s f-string of err is only the message.

01:06 Run the port on December’s export. What name does its line print in the parentheses? Your turn: pause the video and predict.

01:21 Error. Not ExportMissingError, only the word Error. Nothing crashed, the message is right, and the exit code is one, as in Python.

01:33 But the report no longer tells Joan which problem stopped the import.

01:39 JavaScript does know the class. The instanceof check matched it as a DonationError, or this branch wouldn’t have run.

01:49 And its class’s own name, err.constructor.name, is ExportMissingError, as you’d expect. But name isn’t the class’s name.

02:00 It’s a property of the error, and neither of your classes sets one: their bodies are empty.

02:07 So JavaScript looks the name up. The error doesn’t hold one, so it falls back to its class’s prototype, then the class above’s, then Error.prototype at the end.

02:20 There, name is Error, and every error whose classes don’t set one inherits it. A built-in RangeError’s prototype sets its own name.

02:31 It’s like a Python instance falling back to class attributes, except JavaScript keeps them on the prototype, a separate object. As in Python, the class’s name isn’t on that path: err.constructor.name asks the class.

02:47 Prototypes get a course of their own later.

02:51 Node’s own crash output reads the class itself. In a test file, throw a BadRowError that nothing catches, and the crash still says BadRowError, with its fields after the stack.

03:05 So does console.error(err). But the error as text and your report both say Error, so a test crash won’t show you the slip. Your report could print err.constructor.name instead, but the error as text still says Error, so fix the base class, once.

03:27 DonationError gets a constructor that passes a message and options up to super() unchanged. The options are for the next section.

03:37 this.name gets new.target.name as its value. Inside a constructor, like type(self) in a Python .__init__(), new.target is the class that new was called on.

03:50 For a new ExportMissingError, that’s ExportMissingError, even though the constructor belongs to DonationError.

04:00 ExportMissingError has no constructor of its own, so it gets one that passes its arguments up to this one. Run the port again, and the line names ExportMissingError, as Python’s does.

04:13 BadRowError’s own constructor calls super(), and new.target is still the class you created, so its name is BadRowError.

04:22 The error as text started with plain Error last lesson. Now it starts with ExportMissingError, and your report still uses the bare message.

04:35 A JavaScript developer names every class once, in the program’s base class, so any class you add later names itself. You’ll also see name set by hand in each class, as a field: it works, but it must match the class name.

04:51 Next up, Report Each Rejected Pledge: on the food bank’s pledge form, you’ll report each rejected pledge’s problem by name and message, as the Python does.

Become a Member to join the conversation.