Custom errors in JavaScript
Subclassing Error to carry structured failure data.
class ValidationError extends Error {
constructor(field) {
super(`invalid field: ${field}`);
this.name = "ValidationError";
this.field = field;
}
}
function validate(user) {
if (!user.email) throw new ValidationError("email");
return user;
}
try {
validate({});
} catch (error) {
if (error instanceof ValidationError) console.warn(error.field);
else throw error;
}
How it works
extends Errorandsuper(message)set up the class.- Extra fields like
fieldtravel with the error. instanceofdistinguishes it; re-throw the rest.
Keywords and builtins used here
catchclassconstructorelseextendsfunctionifreturnsuperthisthrowtry
The run, in numbers
- Lines
- 19
- Characters to type
- 366
- Tokens
- 92
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 55 seconds.
Step 1 of 2 in Errors, step 38 of 43 in Language basics.