Errors, Debugging and Modules
Programs meet bad input and broken assumptions. Catch errors with try and catch, throw your own with a clear message, step through code with the debugger, and split a program into modules that import and export.
Updated
Errors in JavaScript
- Handling Errors with try, catch and finally (Apprentice): try runs code that might fail, catch takes over when it does and gets an error object with a name and a message, and finally runs either way, so one bad value doesn't stop your whole program.
- Throwing Your Own Errors (Journeyman): When a function gets a value it can't use, throw new Error with a message that says what was wrong, make your own error class with extends Error for the problems your program knows about, and return a value instead when there's no mistake to report.
Debugging JavaScript
- Debugging with Breakpoints (Apprentice): A debugger pauses your program at a breakpoint, lets you run it one line at a time, and shows every variable's value as you go, in VS Code for Node and in the browser's DevTools for a page, so you can see the line where a value goes wrong.
Modules in JavaScript
- Modules: import and export (Apprentice): A module is a file that shares only what it exports; another file imports it by name (a named export) or under a name it picks (the default export), and a package.json in Node or type="module" on a page makes it run.
Exercise: Recipe Scaler
- Exercise: Recipe Scaler (Journeyman): Finish a recipe scaler split into modules, which converts cups to milliliters, scales a recipe from 4 servings to 10 and refuses bad servings with a ServingsError, and let the tests check each piece and each error.
Up Next: JavaScript in the Browser
- Up Next: JavaScript in the Browser (Apprentice): Module 3 gave you the tools for bigger programs (closures, classes, your own errors, the debugger and modules); this lesson shows which one fits which job, the Virtual Pet project that uses them all, and how Module 4 puts your code in charge of a web page.