Handling Multiple Error Types
Provide code examples for differentiating and handling various error types (e.g., network vs API errors) within QueryErrorResetBoundary, using the error object returned by useQuery.
const { data, error } = useQuery(['fetchData'], fetchDataFunction, {
// Enabling error propagation to the Error Boundary
useErrorBoundary: (error) => {
// Network errors
if (!error.response) return true;
// Specific API error status codes
return error.response.status >= 500;
}
});
This code snippet is from a component using React Query's useQuery hook to fetch some data. It specifies that network errors (errors without a response property) and server errors (status code 500 and above) should be propagated to an Error Boundary, while other errors (like client-side errors, status code 400-499) can be handled within the component itself.
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary
onReset={reset}
fallbackRender={({ error, resetErrorBoundary }) => {
// Custom rendering based on error type
let errorMessage = 'Something went wrong';
if (!error.response) errorMessage = 'Network error, please try again';
else if (error.response.status === 404) errorMessage = 'Data not found';
return (
<div>
<p>{errorMessage}</p>
<button onClick={() => resetErrorBoundary()}>Try Again</button>
</div>
);
}}
>
<YourComponent />
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
This code block wraps a component within QueryErrorResetBoundary and an ErrorBoundary. It customizes the fallback component based on the type of error received. For network errors (no response object), it displays a 'Network error' message. For 404 errors, it specifies 'Data not found'. For all other errors, it defaults to 'Something went wrong'. This provides a more user-friendly error feedback depending on the error encountered.