@orchard9ai/error-handling
Version:
Federated error handling package with go-core-http-toolkit format support and logging integration
129 lines (99 loc) • 2.98 kB
Markdown
Graceful HTTP error handling for React applications. Prevents crashes from API errors and provides user-friendly error messages.
```bash
npm install @orchard9ai/error-handling
```
```typescript
import { useHttpClient, ToastProvider, installGlobalErrorHandling } from '@orchard9ai/error-handling';
// 1. Wrap your app with ToastProvider
function App() {
return (
<ToastProvider>
<YourApp />
</ToastProvider>
);
}
// 2. Use the HTTP client in components
function MyComponent() {
const http = useHttpClient({
baseUrl: 'http://localhost:25820/api/v1'
});
const handleSubmit = async (data) => {
try {
const result = await http.post('/organizations/register', data);
console.log('Success:', result.data);
} catch (error) {
// Error automatically shown as toast
// No app crashes!
}
};
}
```
- **No More Crashes**: 409 conflicts and other HTTP errors show friendly toasts instead of crashing
- **Auto Cleanup**: Requests automatically abort when components unmount
- **XSS Safe**: All error messages are sanitized
- **React Ready**: Hooks for easy integration
React hook that creates an HTTP client with automatic cleanup.
```typescript
const http = useHttpClient({
baseUrl: 'https://api.example.com',
timeout: 30000,
enableRetry: false, // Default: false
showToasts: true, // Default: true
});
// Make requests
const response = await http.get('/users');
const response = await http.post('/users', { name: 'John' });
const response = await http.put('/users/1', { name: 'Jane' });
const response = await http.delete('/users/1');
```
Required wrapper component for toast notifications.
```jsx
<ToastProvider config={{
position: 'top-right',
autoHideDuration: 5000
}}>
<App />
</ToastProvider>
```
Optional: Catch unhandled errors globally.
```typescript
installGlobalErrorHandling({
showToasts: true,
logToConsole: true,
ignoredErrors: ['ResizeObserver loop limit exceeded']
});
```
Automatically handles API errors in this format:
```json
{
"error": "conflict",
"message": "Organization already exists",
"code": "organization_conflict",
"correlation_id": "err_9c20308c",
"details": {
"field": "name",
"value": "Already exists"
}
}
```
1. **Always use `useHttpClient`** for HTTP requests (not raw fetch)
2. **Wrap your app** with `ToastProvider`
3. **Let errors bubble up** - they'll be shown as toasts automatically
4. **Don't enable retry** unless you have specific backoff requirements
5. **Configure base URL** once and reuse the client
## Security
- All error messages are HTML-escaped to prevent XSS
- Sensitive fields (password, token, api_key) are automatically filtered
- Stack traces are never shown to users
## License
MIT