297 lines
7.6 KiB
Markdown
297 lines
7.6 KiB
Markdown
# Simple API Error Handling with PrimeVue Toast
|
|
|
|
This guide shows how to implement clean, simple error handling using PrimeVue Toast instead of complex custom notification components.
|
|
|
|
## Overview
|
|
|
|
The simplified approach provides:
|
|
|
|
- **Automatic error toasts** using PrimeVue Toast
|
|
- **Loading state management** with component-specific tracking
|
|
- **Success notifications** for create/update operations
|
|
- **Retry logic** with exponential backoff
|
|
- **Clean error storage** for debugging and component-specific error handling
|
|
|
|
## Key Files
|
|
|
|
### 1. PrimeVue Notification Store
|
|
|
|
**File:** `/src/stores/notifications-primevue.js`
|
|
|
|
```javascript
|
|
import { ref } from "vue";
|
|
import { defineStore } from "pinia";
|
|
|
|
export const useNotificationStore = defineStore(
|
|
"notifications-primevue",
|
|
() => {
|
|
// Toast instance reference
|
|
const toastInstance = ref(null);
|
|
|
|
// Set the toast instance (called from App.vue)
|
|
const setToastInstance = (toast) => {
|
|
toastInstance.value = toast;
|
|
};
|
|
|
|
// Convenience methods for different toast types
|
|
const addSuccess = (message, life = 4000) => {
|
|
if (toastInstance.value) {
|
|
toastInstance.value.add({
|
|
severity: "success",
|
|
summary: "Success",
|
|
detail: message,
|
|
life,
|
|
});
|
|
}
|
|
};
|
|
|
|
// ... other methods
|
|
},
|
|
);
|
|
```
|
|
|
|
### 2. Enhanced API Wrapper
|
|
|
|
**File:** `/src/api-toast.js`
|
|
|
|
Provides a wrapper around your existing API calls with automatic:
|
|
|
|
- Error handling and toast notifications
|
|
- Loading state management
|
|
- Component-specific error tracking
|
|
- Retry logic
|
|
- Success messages
|
|
|
|
```javascript
|
|
// Simple usage - automatic error toasts
|
|
try {
|
|
const result = await ApiWithToast.getClientStatusCounts();
|
|
// Success - data loaded
|
|
} catch (error) {
|
|
// Error toast automatically shown
|
|
}
|
|
|
|
// Create operations with success toasts
|
|
await ApiWithToast.createClient(formData);
|
|
// Shows: "Client created successfully!"
|
|
```
|
|
|
|
## Usage in Components
|
|
|
|
### 1. Basic Setup
|
|
|
|
In your component:
|
|
|
|
```vue
|
|
<script setup>
|
|
import ApiWithToast from "@/api-toast";
|
|
import { useErrorStore } from "@/stores/errors";
|
|
import { useLoadingStore } from "@/stores/loading";
|
|
|
|
const errorStore = useErrorStore();
|
|
const loadingStore = useLoadingStore();
|
|
|
|
// Simple API call
|
|
const loadData = async () => {
|
|
try {
|
|
const result = await ApiWithToast.getPaginatedClientDetails(
|
|
pagination,
|
|
filters,
|
|
[],
|
|
);
|
|
// Handle success
|
|
} catch (error) {
|
|
// Error toast shown automatically
|
|
// Component error stored automatically
|
|
}
|
|
};
|
|
</script>
|
|
```
|
|
|
|
### 2. Loading States
|
|
|
|
The API wrapper automatically manages loading states:
|
|
|
|
```vue
|
|
<template>
|
|
<Button
|
|
@click="loadClients"
|
|
:loading="loadingStore.isComponentLoading('clients')"
|
|
label="Load Clients"
|
|
/>
|
|
</template>
|
|
```
|
|
|
|
### 3. Component-Specific Errors
|
|
|
|
Access errors for debugging or custom handling:
|
|
|
|
```vue
|
|
<template>
|
|
<div v-if="errorStore.getComponentError('clients')" class="error-info">
|
|
Error: {{ errorStore.getComponentError("clients").message }}
|
|
</div>
|
|
</template>
|
|
```
|
|
|
|
## App.vue Integration
|
|
|
|
Ensure your `App.vue` includes the Toast component and connects it to the store:
|
|
|
|
```vue
|
|
<template>
|
|
<div id="app">
|
|
<!-- Your app content -->
|
|
<router-view />
|
|
|
|
<!-- PrimeVue Toast for notifications -->
|
|
<Toast ref="toast" />
|
|
</div>
|
|
</template>
|
|
|
|
<script setup>
|
|
import { ref, onMounted } from "vue";
|
|
import Toast from "primevue/toast";
|
|
import { useNotificationStore } from "@/stores/notifications-primevue";
|
|
|
|
const toast = ref();
|
|
const notificationStore = useNotificationStore();
|
|
|
|
onMounted(() => {
|
|
// Connect toast instance to the store
|
|
notificationStore.setToastInstance(toast.value);
|
|
});
|
|
</script>
|
|
```
|
|
|
|
## API Wrapper Methods
|
|
|
|
### Convenience Methods
|
|
|
|
Pre-configured methods for common operations:
|
|
|
|
```javascript
|
|
// Data fetching (no success toast)
|
|
await ApiWithToast.getClientStatusCounts();
|
|
await ApiWithToast.getPaginatedClientDetails(pagination, filters, sorting);
|
|
await ApiWithToast.getPaginatedJobDetails(pagination, filters, sorting);
|
|
await ApiWithToast.getPaginatedWarrantyData(pagination, filters, sorting);
|
|
|
|
// Create operations (success toast included)
|
|
await ApiWithToast.createClient(clientData);
|
|
|
|
// Utility operations (with retry logic)
|
|
await ApiWithToast.getCityStateByZip(zipcode);
|
|
```
|
|
|
|
### Custom API Calls
|
|
|
|
For custom operations:
|
|
|
|
```javascript
|
|
await ApiWithToast.makeApiCall(() => yourApiFunction(), {
|
|
componentName: "myComponent",
|
|
showSuccessToast: true,
|
|
successMessage: "Operation completed!",
|
|
showErrorToast: true,
|
|
customErrorMessage: "Custom error message",
|
|
retryCount: 3,
|
|
retryDelay: 1000,
|
|
showLoading: true,
|
|
loadingMessage: "Processing...",
|
|
});
|
|
```
|
|
|
|
## Configuration Options
|
|
|
|
| Option | Type | Default | Description |
|
|
| -------------------- | ------- | -------------- | ----------------------------------------------- |
|
|
| `componentName` | string | null | Component identifier for error/loading tracking |
|
|
| `showErrorToast` | boolean | true | Show error toast on failure |
|
|
| `showSuccessToast` | boolean | false | Show success toast on completion |
|
|
| `showLoading` | boolean | true | Show loading indicator |
|
|
| `loadingMessage` | string | 'Loading...' | Loading message to display |
|
|
| `successMessage` | string | null | Success message for toast |
|
|
| `customErrorMessage` | string | null | Override error message |
|
|
| `retryCount` | number | 0 | Number of retry attempts |
|
|
| `retryDelay` | number | 1000 | Delay between retries (ms) |
|
|
| `operationKey` | string | auto-generated | Unique identifier for operation |
|
|
|
|
## Demo Pages
|
|
|
|
### 1. Simple API Demo
|
|
|
|
**URL:** `/dev/simple-api-demo`
|
|
|
|
Shows practical usage with real API calls:
|
|
|
|
- Loading client data
|
|
- Creating test clients
|
|
- Error handling
|
|
- Retry logic
|
|
|
|
### 2. PrimeVue Toast Demo
|
|
|
|
**URL:** `/dev/toast-demo`
|
|
|
|
Demonstrates Toast types and error store integration:
|
|
|
|
- Different toast severities
|
|
- Error store testing
|
|
- API simulation
|
|
|
|
## Migration from Custom Notifications
|
|
|
|
### Old Approach (Custom NotificationDisplay)
|
|
|
|
```vue
|
|
<!-- Complex setup needed -->
|
|
<NotificationDisplay />
|
|
|
|
<script setup>
|
|
import { useNotificationStore } from "@/stores/notifications";
|
|
// Manual notification management
|
|
</script>
|
|
```
|
|
|
|
### New Approach (PrimeVue Toast)
|
|
|
|
```vue
|
|
<!-- Just use the API wrapper -->
|
|
<script setup>
|
|
import ApiWithToast from "@/api-toast";
|
|
// Automatic toast notifications
|
|
</script>
|
|
```
|
|
|
|
## Benefits
|
|
|
|
1. **Consistency**: Uses PrimeVue components throughout
|
|
2. **Simplicity**: No custom notification components needed
|
|
3. **Automatic**: Error handling happens automatically
|
|
4. **Flexible**: Easy to customize per operation
|
|
5. **Maintainable**: Centralized error handling logic
|
|
6. **Type Safety**: Clear API with documented options
|
|
|
|
## Testing
|
|
|
|
Test the implementation by:
|
|
|
|
1. Visit `/dev/simple-api-demo`
|
|
2. Try different operations:
|
|
- Load Clients (success case)
|
|
- Create Test Client (success with toast)
|
|
- Test Error (error toast)
|
|
- Test Retry (retry logic demonstration)
|
|
|
|
The toasts will appear in the top-right corner using PrimeVue's default styling.
|
|
|
|
## Next Steps
|
|
|
|
1. Replace existing API calls with `ApiWithToast` methods
|
|
2. Remove custom notification components
|
|
3. Update components to use the simplified error handling
|
|
4. Test across all your existing workflows
|
|
|
|
This approach provides cleaner, more maintainable error handling while leveraging your existing PrimeVue setup.
|