π Prefer URL.canParse() over constructing a URL in a try/catch for validation.
πΌ This rule is enabled in the following configs: β
recommended, βοΈ unopinionated.
π§ This rule is automatically fixable by the --fix CLI option.
Prefer URL.canParse() over constructing a URL in a try/catch block for validation.
URL.canParse() returns whether a string or stringifiable input can be parsed as a URL without constructing a URL object.
This rule intentionally only reports simple boolean validation patterns. It assumes the URL input is a normal string or stringifiable value and does not rewrite arbitrary try/catch control flow. It also skips commented try/catch bodies and obviously unsafe argument expressions, such as expressions with side effects or inline values whose stringification/conversion could throw.
// β
try {
new URL(value);
return true;
} catch {
return false;
}
// β
return URL.canParse(value);// β
let valid;
try {
new URL(value, base);
valid = true;
} catch {
valid = false;
}
// β
let valid;
valid = URL.canParse(value, base);