Trung BìnhState Management iconState Management

Cách xử lý error trong React Query?

React Query v5 thay đổi error handling so với v4: onError callback bị deprecated, thay bằng throwOnError hoặc meta.

  • Retry strategies: mặc định retry 3 lần, exponential backoff — override: retry: (failureCount, error) => error.status !== 401 && failureCount < 3 để không retry auth errors.
  • Global error handling với QueryCache observer: new QueryClient({ queryCache: new QueryCache({ onError: (error, query) => { if (query.meta?.showErrorToast) toast.error(error.message) } }) }) — per-query opt-in: useQuery({ ..., meta: { showErrorToast: true } }).
  • Error Boundary integration: throwOnError: true khiến query throw error lên Error Boundary thay vì return isError.
  • Hoặc dùng useSuspenseQuery — tự động throw lên Error Boundary. error.message vs error.response.data: với fetch API, HTTP errors không tự throw — phải check if (!res.ok) throw new Error(res.statusText) trong queryFn.

Pitfall v5: onError ở useMutation vẫn hoạt động nhưng global onError trong defaultOptions đã bị xóa.

Xem toàn bộ State Management cùng filter theo level & chủ đề con.

Mở danh sách State Management