@orchard9ai/error-handling
v0.1.2
Published
Federated error handling package with go-core-http-toolkit format support and logging integration
Readme
@orchard9ai/error-handling
Graceful HTTP error handling for React applications. Prevents crashes from API errors and provides user-friendly error messages.
Installation
npm install @orchard9ai/error-handlingQuick Start
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!
}
};
}Key Features
- 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
API Reference
useHttpClient(config)
React hook that creates an HTTP client with automatic cleanup.
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');ToastProvider
Required wrapper component for toast notifications.
<ToastProvider config={{
position: 'top-right',
autoHideDuration: 5000
}}>
<App />
</ToastProvider>installGlobalErrorHandling(config)
Optional: Catch unhandled errors globally.
installGlobalErrorHandling({
showToasts: true,
logToConsole: true,
ignoredErrors: ['ResizeObserver loop limit exceeded']
});Error Format
Automatically handles API errors in this format:
{
"error": "conflict",
"message": "Organization already exists",
"code": "organization_conflict",
"correlation_id": "err_9c20308c",
"details": {
"field": "name",
"value": "Already exists"
}
}Best Practices
- Always use
useHttpClientfor HTTP requests (not raw fetch) - Wrap your app with
ToastProvider - Let errors bubble up - they'll be shown as toasts automatically
- Don't enable retry unless you have specific backoff requirements
- 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
