Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: general
javascripturlerror-handlingrobustnesssafety

Safeguard URL instantiation with try-catch

Wrap `new URL()` calls in try-catch blocks to prevent runtime crashes from malformed strings.

PR: Feat/FCK-1669 - Adding Job Landing Page #3656Created: Dec 8, 2025

Bad example

Old codetsx
1const normalizeUrl = (link: string) => {
2 // ❌ Crashes if 'link' is empty, partial, or malformed
3 return new URL(link).href;
4};
5
6const Component = ({ url }) => (
7 <a href={normalizeUrl(url)}>Open</a>
8);

Explanation (EN)

Directly calling `new URL()` with dynamic input allows invalid strings to throw an error. This unhandled exception bubbles up and can crash the entire component tree or application.

Objašnjenje (HR)

Izravno pozivanje `new URL()` s dinamičkim unosom omogućuje da neispravni stringovi bace grešku. Ova neobrađena iznimka može srušiti cijelo stablo komponenti ili aplikaciju.

Good example

New codetsx
1const normalizeUrl = (link: string): string | null => {
2 try {
3 // ✅ Safely handles bad input by returning null
4 return new URL(link).href;
5 } catch {
6 return null;
7 }
8};
9
10const Component = ({ url }) => {
11 const safeUrl = normalizeUrl(url);
12 if (!safeUrl) return null;
13 return <a href={safeUrl}>Open</a>;
14};

Explanation (EN)

Wrapping the constructor in a `try-catch` block ensures that invalid URLs are handled gracefully (e.g., returning `null`). This prevents crashes and allows the UI to decide whether to hide the link or show a fallback.

Objašnjenje (HR)

Omotavanje konstruktora u `try-catch` blok osigurava da se neispravni URL-ovi obrađuju bezbolno (npr. vraćanjem `null`). To sprječava rušenje aplikacije i omogućuje UI-u da odluči hoće li sakriti poveznicu ili prikazati zamjenski sadržaj.

Notes (EN)

Even with protocol checks (like regex), `new URL()` can still fail on specific malformed characters or incomplete strings.