Rules Hub
Coding Rules Library
Limit the scope of try-catch blocks
Wrap only unstable code (like I/O) in try-catch blocks, keeping data transformation logic outside.
Bad example
| 1 | async function getFormattedTickers(ids: string[]) { |
| 2 | try { |
| 3 | // I/O operation |
| 4 | const tickers = await api.fetchTickers(ids); |
| 5 |
|
| 6 | // Data transformation logic mixed inside the try block |
| 7 | return tickers.map((t) => ({ |
| 8 | slug: t.symbol.toLowerCase(), |
| 9 | name: t.name.trim(), |
| 10 | // If 't' is null here, it throws a TypeError which is caught below |
| 11 | // masking a bug as a network error |
| 12 | price: t.price.toFixed(2), |
| 13 | })); |
| 14 | } catch (error) { |
| 15 | console.error('Failed to load tickers', error); |
| 16 | return []; |
| 17 | } |
| 18 | } |
Explanation (EN)
The entire logic is wrapped in `try-catch`. If the mapping logic throws a `TypeError` (e.g., accessing properties on undefined), it is caught and treated as a fetch failure, hiding the actual bug.
Objašnjenje (HR)
Cijela logika je omotana u `try-catch`. Ako logika mapiranja baci `TypeError` (npr. pristup svojstvima na `undefined`), greška se hvata i tretira kao neuspjeh dohvaćanja, skrivajući stvarni bug.
Good example
| 1 | async function getFormattedTickers(ids: string[]) { |
| 2 | let tickers = []; |
| 3 |
|
| 4 | // 1. Wrap only the code that can fail due to external factors (I/O) |
| 5 | try { |
| 6 | tickers = await api.fetchTickers(ids); |
| 7 | } catch (error) { |
| 8 | console.error('Failed to load tickers', error); |
| 9 | return []; |
| 10 | } |
| 11 |
|
| 12 | // 2. Perform transformation logic outside. |
| 13 | // Use defensive coding (null checks) instead of try-catch for logic. |
| 14 | if (!tickers || !Array.isArray(tickers)) return []; |
| 15 |
|
| 16 | return tickers |
| 17 | .filter((t) => t && t.symbol) |
| 18 | .map((t) => ({ |
| 19 | slug: t.symbol.toLowerCase(), |
| 20 | name: t.name ? t.name.trim() : 'Unknown', |
| 21 | price: typeof t.price === 'number' ? t.price.toFixed(2) : '-', |
| 22 | })); |
| 23 | } |
Explanation (EN)
The `try-catch` block is limited to the API call. Data processing happens outside, using explicit checks for null values. Runtime bugs in logic will now properly throw or be handled explicitly, rather than being swallowed by the network error handler.
Objašnjenje (HR)
`try-catch` blok je ograničen samo na API poziv. Obrada podataka događa se izvan njega, koristeći eksplicitne provjere za null vrijednosti. Runtime bugovi u logici sada će se ispravno srušiti ili biti obrađeni, umjesto da budu progutani kao mrežne greške.