Build an explicit error strategy with dedicated classes, well-placed catch boundaries, and a console used to its full potential.
Open this lesson in KodokonRobustness is not about catching every error, but about catching them in the right place. Field rule: fail fast and loudly as close to the bug as possible (validation, invariants), and only catch at the boundaries where you can actually react: show a message, retry, log. A try/catch that does nothing useful does not make the code safer; it makes failures silent.
function parseConfig(json) {
try {
return JSON.parse(json);
} catch (error) {
console.error("Unreadable config:", error.message);
throw error; // rethrow: nothing can be fixed here
} finally {
console.log("Finished reading configuration");
}
}Plain strings do not make an error strategy. Extend Error to create classes carrying structured data (HTTP status, invalid field) that can be discriminated with instanceof. Since ES2022, the cause option chains the original error to the high-level one: you expose a clear business message without losing the technical trail.
class ApiError extends Error {
constructor(message, status, options) {
super(message, options);
this.name = "ApiError";
this.status = status;
}
}
try {
const low = new Error("socket timeout");
throw new ApiError("Profile unavailable", 503,
{ cause: low });
} catch (error) {
if (error instanceof ApiError) {
console.error(error.status, error.cause.message);
}
}The console offers much more than log: console.table lines up collections of objects, group/groupEnd nests output, time/timeEnd measures a duration, console.assert only logs when the condition is false, and console.trace prints the current call stack. Combined, these tools beat a downpour of anonymous log calls hands down.
const users = [
{ name: "Ada", role: "admin" },
{ name: "Linus", role: "dev" },
];
console.table(users);
console.group("Checks");
console.assert(users.length > 0, "Empty list");
console.time("sort");
users.sort((a, b) => a.name.localeCompare(b.name));
console.timeEnd("sort");
console.groupEnd();finally block run?cause option for when constructing an error?console.assert(condition, message)?