Lesson 26 of 56 · Typescript
Custom Error Types
Duration: 15 minutes
Extending Error
class ValidationError extends Error {
constructor(public field: string, message: string) {
super(message);
this.name = "ValidationError";
}
}
function assertPositive(n: number) {
if (n < 0) throw new ValidationError("n", "must be positive");
}
Type Guard for custom errors
function isValidationError(e: unknown): e is ValidationError {
return e instanceof ValidationError;
}
try {
assertPositive(-5);
} catch (e) {
if (isValidationError(e)) console.error(e.field, e.message);
}