Skip to content

Latest commit

Β 

History

History
45 lines (33 loc) Β· 1.33 KB

File metadata and controls

45 lines (33 loc) Β· 1.33 KB

prefer-url-can-parse

πŸ“ 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.

Examples

// ❌
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);