v1.4.2

Error Handling

Because BoltFetch returns a predictable object for every request, robust error handling is significantly easier compared to using standard try/catch blocks.

The BoltFetchError Shape

When response.success is false, the returned object is a BoltFetchError. It provides rich context about exactly what went wrong.

typescript
import { boltfetch } from "boltfetch"; const response = await boltfetch.get('/api/health'); if (!response.success) { console.log(response.status); // HTTP Status Code (e.g., 404, 500, or 0 for network error) console.log(response.message); // Human readable message console.log(response.url); // The requested URL console.log(response.method); // The requested Method (e.g. "GET") console.log(response.moreInfo); // Parsed JSON error payload from the server, if any }

HTTP Status Handling Strategy

A robust frontend application should handle different error bands distinctly.

1. Network Errors & Timeouts

When a request never reaches the server, the connection is severed, or the request times out, the status will typically be 0 or undefined, and response.success is false.

  • The message will clarify if it was a timeout or network failure.

2. Client Errors (status >= 400 && status < 500)

These errors indicate that your application sent a bad request.

  • 400 Bad Request: Usually validation failures. Look at response.moreInfo for specifics.
  • 401 Unauthorized: The user's session expired. Usually intercepted globally to trigger a refresh or redirect to login.
  • 403 Forbidden: The user lacks permissions. Show a "Permission Denied" UI.
  • 404 Not Found: The requested resource doesn't exist. Redirect to a 404 page or show empty state.

3. Server Errors (status >= 500)

These indicate a crash or issue on the backend API.

  • Show a generic "Something went wrong on our end" toast message.

Global Error Strategy

Instead of handling generic errors in every single component, you can use Response Interceptors.

Global Interceptor (For 401s and 500s):

typescript
import { configureBoltFetchClient } from "boltfetch"; import { toast } from 'react-hot-toast'; const client = configureBoltFetchClient({ responseInterceptor: (response) => { if (!response.success) { if (response.status >= 500) { toast.error("Server is currently down. Try again later."); } if (response.status === 401) { // Handle redirect to login window.location.href = "/login"; } } return response; } });

Local Component (For 400s and 404s):

typescript
// Inside your UI component const response = await client.post('/api/posts', postData); if (!response.success) { if (response.status === 400) { setFormErrors(response.moreInfo.validationErrors); } else if (response.status === 404) { toast.error("Category not found."); } } else { toast.success("Post created!"); }