Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: react
fetchasyncerror-handlingreactclean-code

Identify aborted requests by error type

Check for 'AbortError' explicitly in catch blocks instead of relying on signal state to handle cancellations.

PR: Feat/FCK-1623 - Adding eAvis widget to the sidebar #3643Created: Dec 8, 2025

Bad example

Old codets
1useEffect(() => {
2 const controller = new AbortController();
3 const { signal } = controller;
4
5 fetch('/api/data', { signal })
6 .then(res => res.json())
7 .catch(err => {
8 // Unreliable: checks signal state instead of error type
9 if (!signal.aborted) {
10 console.error(err);
11 setError(true);
12 }
13 });
14
15 return () => controller.abort();
16}, []);

Explanation (EN)

Checking `!signal.aborted` inside `.catch()` is semantically incorrect and potentially unreliable. It relies on shared state rather than the specific error object that caused the rejection.

Objašnjenje (HR)

Provjera `!signal.aborted` unutar `.catch()` je semantički netočna i potencijalno nepouzdana. Oslanja se na dijeljeno stanje umjesto na specifičan objekt greške koji je uzrokovao odbijanje.

Good example

New codets
1useEffect(() => {
2 const controller = new AbortController();
3 const { signal } = controller;
4
5 fetch('/api/data', { signal })
6 .then(res => res.json())
7 .catch(err => {
8 // Reliable: explicitly ignores intentional aborts
9 if (err instanceof DOMException && err.name === 'AbortError') {
10 return;
11 }
12 console.error(err);
13 setError(true);
14 });
15
16 return () => controller.abort();
17}, []);

Explanation (EN)

Explicitly checks if the error is an `AbortError`. This safely filters out intentional cancellations (which are not bugs) while ensuring all other unexpected errors are logged and handled.

Objašnjenje (HR)

Eksplicitno provjerava je li greška `AbortError`. Ovo sigurno filtrira namjerna otkazivanja (koja nisu bugovi), dok osigurava da se sve ostale neočekivane greške bilježe i obrađuju.

Notes (EN)

In `.then()` blocks, checking `!signal.aborted` is still acceptable to prevent state updates after unmount if the promise resolved before abortion.

Bilješke (HR)

U `.then()` blokovima, provjera `!signal.aborted` je i dalje prihvatljiva kako bi se spriječilo ažuriranje stanja nakon unmounta ako je promise riješen prije prekida.