feat: Implement comprehensive error handling and production deployment pipeline
Some checks failed
ParentFlow CI/CD Pipeline / Backend Tests (push) Has been cancelled
ParentFlow CI/CD Pipeline / Frontend Tests (push) Has been cancelled
ParentFlow CI/CD Pipeline / Security Scanning (push) Has been cancelled
ParentFlow CI/CD Pipeline / Build Docker Images (map[context:maternal-app/maternal-app-backend dockerfile:Dockerfile.production name:backend]) (push) Has been cancelled
ParentFlow CI/CD Pipeline / Build Docker Images (map[context:maternal-web dockerfile:Dockerfile.production name:frontend]) (push) Has been cancelled
ParentFlow CI/CD Pipeline / Deploy to Development (push) Has been cancelled
ParentFlow CI/CD Pipeline / Deploy to Production (push) Has been cancelled
CI/CD Pipeline / Lint and Test (push) Has been cancelled
CI/CD Pipeline / E2E Tests (push) Has been cancelled
CI/CD Pipeline / Build Application (push) Has been cancelled
Some checks failed
ParentFlow CI/CD Pipeline / Backend Tests (push) Has been cancelled
ParentFlow CI/CD Pipeline / Frontend Tests (push) Has been cancelled
ParentFlow CI/CD Pipeline / Security Scanning (push) Has been cancelled
ParentFlow CI/CD Pipeline / Build Docker Images (map[context:maternal-app/maternal-app-backend dockerfile:Dockerfile.production name:backend]) (push) Has been cancelled
ParentFlow CI/CD Pipeline / Build Docker Images (map[context:maternal-web dockerfile:Dockerfile.production name:frontend]) (push) Has been cancelled
ParentFlow CI/CD Pipeline / Deploy to Development (push) Has been cancelled
ParentFlow CI/CD Pipeline / Deploy to Production (push) Has been cancelled
CI/CD Pipeline / Lint and Test (push) Has been cancelled
CI/CD Pipeline / E2E Tests (push) Has been cancelled
CI/CD Pipeline / Build Application (push) Has been cancelled
## Error Handling System - Add centralized error handling utilities (errorHandler.ts) - Create reusable error components (ErrorMessage, ErrorToast) - Implement multilingual error support (preserves backend error messages in 5 languages) - Update 15+ forms and components with consistent error handling - Auth forms: login, register, forgot-password - Family management: family page, join family dialog - Child management: child dialog - All tracking forms: feeding, sleep, diaper, medicine, growth, activity ## Production Build Fixes - Fix backend TypeScript errors: InviteCode.uses → InviteCode.useCount (5 instances) - Remove non-existent savedFamily variable from registration response - Fix admin panel TypeScript errors: SimpleMDE toolbar type, PieChart label type ## User Experience Improvements - Auto-uppercase invite code and share code inputs - Visual feedback for case conversion with helper text - Improved form validation with error codes ## CI/CD Pipeline - Create comprehensive production deployment checklist (PRODUCTION_DEPLOYMENT_CHECKLIST.md) - Add automated pre-deployment check script (pre-deploy-check.sh) - Validates frontend, backend, and admin panel builds - Checks git status, branch, and sync state - Verifies environment files and migrations - Add quick start deployment guide (DEPLOYMENT_QUICK_START.md) - Add production deployment automation template (deploy-production.sh) ## Cleanup - Remove outdated push notifications documentation files - Remove outdated PWA implementation plan 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -15,30 +15,31 @@ import { Email, ArrowBack } from '@mui/icons-material';
|
||||
import { motion } from 'framer-motion';
|
||||
import Link from 'next/link';
|
||||
import apiClient from '@/lib/api/client';
|
||||
import { useErrorMessage } from '@/components/common/ErrorMessage';
|
||||
import { formatErrorMessage } from '@/lib/utils/errorHandler';
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
const [email, setEmail] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const { error, showError, clearError, hasError } = useErrorMessage();
|
||||
const [success, setSuccess] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!email.trim()) {
|
||||
setError('Please enter your email address');
|
||||
showError({ message: 'Please enter your email address', code: 'VALIDATION_EMAIL_REQUIRED' });
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError('');
|
||||
clearError();
|
||||
|
||||
try {
|
||||
await apiClient.post('/api/v1/auth/password/forgot', { email });
|
||||
setSuccess(true);
|
||||
} catch (err: any) {
|
||||
console.error('Forgot password error:', err);
|
||||
setError(err.response?.data?.message || 'Failed to send reset email. Please try again.');
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -97,9 +98,9 @@ export default function ForgotPasswordPage() {
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
|
||||
{error}
|
||||
{hasError && (
|
||||
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }} onClose={clearError}>
|
||||
{formatErrorMessage(error)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
|
||||
@@ -28,6 +28,8 @@ import { startAuthentication } from '@simplewebauthn/browser';
|
||||
import Link from 'next/link';
|
||||
import { useTranslation } from '@/hooks/useTranslation';
|
||||
import { useTheme } from '@mui/material/styles';
|
||||
import { useErrorMessage } from '@/components/common/ErrorMessage';
|
||||
import { formatErrorMessage } from '@/lib/utils/errorHandler';
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().email('Invalid email address'),
|
||||
@@ -40,7 +42,7 @@ export default function LoginPage() {
|
||||
const { t } = useTranslation('auth');
|
||||
const theme = useTheme();
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { error, showError, clearError, hasError } = useErrorMessage();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isBiometricLoading, setIsBiometricLoading] = useState(false);
|
||||
const [isBiometricSupported, setIsBiometricSupported] = useState(false);
|
||||
@@ -74,7 +76,7 @@ export default function LoginPage() {
|
||||
};
|
||||
|
||||
const handleBiometricLogin = async () => {
|
||||
setError(null);
|
||||
clearError();
|
||||
setIsBiometricLoading(true);
|
||||
|
||||
try {
|
||||
@@ -100,11 +102,11 @@ export default function LoginPage() {
|
||||
} catch (err: any) {
|
||||
console.error('Biometric login failed:', err);
|
||||
if (err.name === 'NotAllowedError') {
|
||||
setError('Biometric authentication was cancelled');
|
||||
showError({ message: 'Biometric authentication was cancelled', code: 'BIOMETRIC_CANCELLED' });
|
||||
} else if (err.name === 'NotSupportedError') {
|
||||
setError('Biometric authentication is not supported on this device');
|
||||
showError({ message: 'Biometric authentication is not supported on this device', code: 'BIOMETRIC_NOT_SUPPORTED' });
|
||||
} else {
|
||||
setError(err.response?.data?.message || err.message || 'Biometric login failed. Please try again.');
|
||||
showError(err);
|
||||
}
|
||||
} finally {
|
||||
setIsBiometricLoading(false);
|
||||
@@ -112,7 +114,7 @@ export default function LoginPage() {
|
||||
};
|
||||
|
||||
const onSubmit = async (data: LoginFormData) => {
|
||||
setError(null);
|
||||
clearError();
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
@@ -127,7 +129,7 @@ export default function LoginPage() {
|
||||
mfaMethod: err.response.data.mfaMethod,
|
||||
});
|
||||
} else {
|
||||
setError(err.message || 'Failed to login. Please check your credentials.');
|
||||
showError(err);
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
@@ -193,9 +195,9 @@ export default function LoginPage() {
|
||||
{t('login.subtitle')}
|
||||
</Typography>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
|
||||
{error}
|
||||
{hasError && (
|
||||
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }} onClose={clearError}>
|
||||
{formatErrorMessage(error)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import Link from 'next/link';
|
||||
import { useTheme } from '@mui/material/styles';
|
||||
import apiClient from '@/lib/api/client';
|
||||
import { useErrorMessage } from '@/components/common/ErrorMessage';
|
||||
import { formatErrorMessage } from '@/lib/utils/errorHandler';
|
||||
|
||||
// Create a function to generate schema dynamically based on requireInviteCode
|
||||
const createRegisterSchema = (requireInviteCode: boolean) => z.object({
|
||||
@@ -79,7 +81,7 @@ export default function RegisterPage() {
|
||||
const theme = useTheme();
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { error, showError, clearError, hasError } = useErrorMessage();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [userAge, setUserAge] = useState<number | null>(null);
|
||||
const [requiresParentalConsent, setRequiresParentalConsent] = useState(false);
|
||||
@@ -150,11 +152,11 @@ export default function RegisterPage() {
|
||||
}, [dateOfBirth]);
|
||||
|
||||
const onSubmit = async (data: RegisterFormData) => {
|
||||
setError(null);
|
||||
clearError();
|
||||
|
||||
// Validate invite code if required
|
||||
if (requireInviteCode && (!data.inviteCode || data.inviteCode.trim() === '')) {
|
||||
setError('Invite code is required to register');
|
||||
showError({ message: 'Invite code is required to register', code: 'VALIDATION_INVITE_CODE_REQUIRED' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -172,7 +174,7 @@ export default function RegisterPage() {
|
||||
});
|
||||
// Navigation to onboarding is handled in the register function
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'Failed to register. Please try again.');
|
||||
showError(err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -224,9 +226,9 @@ export default function RegisterPage() {
|
||||
Start your journey to organized parenting
|
||||
</Typography>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }}>
|
||||
{error}
|
||||
{hasError && (
|
||||
<Alert severity="error" sx={{ mb: 3, borderRadius: 2 }} onClose={clearError}>
|
||||
{formatErrorMessage(error)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@@ -285,14 +287,21 @@ export default function RegisterPage() {
|
||||
label="Invite Code"
|
||||
margin="normal"
|
||||
error={!!errors.inviteCode}
|
||||
helperText={errors.inviteCode?.message || 'Enter your invite code to register'}
|
||||
{...register('inviteCode')}
|
||||
helperText={errors.inviteCode?.message || 'Invite codes are automatically converted to uppercase'}
|
||||
{...register('inviteCode', {
|
||||
setValueAs: (value) => value?.toUpperCase() || '',
|
||||
})}
|
||||
onChange={(e) => {
|
||||
const uppercased = e.target.value.toUpperCase();
|
||||
setValue('inviteCode', uppercased);
|
||||
}}
|
||||
disabled={isLoading}
|
||||
required
|
||||
inputProps={{
|
||||
'aria-required': 'true',
|
||||
'aria-invalid': !!errors.inviteCode,
|
||||
'aria-describedby': errors.inviteCode ? 'invite-code-error' : 'invite-code-helper',
|
||||
style: { textTransform: 'uppercase' },
|
||||
}}
|
||||
InputProps={{
|
||||
sx: { borderRadius: 3 },
|
||||
|
||||
@@ -38,6 +38,8 @@ import { RoleInvitesSection } from '@/components/family/RoleInvitesSection';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useTranslation } from '@/hooks/useTranslation';
|
||||
import { useSelectedFamily } from '@/hooks/useSelectedFamily';
|
||||
import { useErrorMessage } from '@/components/common/ErrorMessage';
|
||||
import { formatErrorMessage } from '@/lib/utils/errorHandler';
|
||||
|
||||
export default function FamilyPage() {
|
||||
const { t } = useTranslation('family');
|
||||
@@ -46,7 +48,7 @@ export default function FamilyPage() {
|
||||
const [family, setFamily] = useState<Family | null>(null);
|
||||
const [members, setMembers] = useState<FamilyMember[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string>('');
|
||||
const { error, showError, clearError, hasError } = useErrorMessage();
|
||||
const [inviteDialogOpen, setInviteDialogOpen] = useState(false);
|
||||
const [joinDialogOpen, setJoinDialogOpen] = useState(false);
|
||||
const [removeDialogOpen, setRemoveDialogOpen] = useState(false);
|
||||
@@ -63,7 +65,7 @@ export default function FamilyPage() {
|
||||
fetchFamilyData();
|
||||
} else {
|
||||
setLoading(false);
|
||||
setError(t('messages.noFamilyFound'));
|
||||
showError({ message: t('messages.noFamilyFound'), code: 'NO_FAMILY_FOUND' });
|
||||
}
|
||||
}, [familyId, selectedIndex]);
|
||||
|
||||
@@ -72,7 +74,7 @@ export default function FamilyPage() {
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError('');
|
||||
clearError();
|
||||
const [familyData, membersData] = await Promise.all([
|
||||
familiesApi.getFamily(familyId),
|
||||
familiesApi.getFamilyMembers(familyId),
|
||||
@@ -86,8 +88,7 @@ export default function FamilyPage() {
|
||||
[familyId]: familyData.name
|
||||
}));
|
||||
} catch (err: any) {
|
||||
console.error('Failed to fetch family data:', err);
|
||||
setError(err.response?.data?.message || t('messages.failedToLoad'));
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -186,8 +187,7 @@ export default function FamilyPage() {
|
||||
setRemoveDialogOpen(false);
|
||||
setMemberToRemove(null);
|
||||
} catch (err: any) {
|
||||
console.error('Failed to remove member:', err);
|
||||
setError(err.response?.data?.message || t('messages.failedToRemove'));
|
||||
showError(err);
|
||||
} finally {
|
||||
setActionLoading(false);
|
||||
}
|
||||
@@ -281,9 +281,9 @@ export default function FamilyPage() {
|
||||
</Paper>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError('')}>
|
||||
{error}
|
||||
{hasError && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={clearError}>
|
||||
{formatErrorMessage(error)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@@ -435,7 +435,7 @@ export default function FamilyPage() {
|
||||
<RoleInvitesSection
|
||||
familyId={familyId!}
|
||||
onSuccess={(message) => setSnackbar({ open: true, message })}
|
||||
onError={(message) => setError(message)}
|
||||
onError={(err) => showError(err)}
|
||||
/>
|
||||
</Grid>
|
||||
)}
|
||||
|
||||
@@ -51,6 +51,8 @@ import { useDispatch, useSelector } from 'react-redux';
|
||||
import { fetchChildren, selectChild, selectSelectedChild, childrenSelectors } from '@/store/slices/childrenSlice';
|
||||
import { AppDispatch, RootState } from '@/store/store';
|
||||
import ChildSelector from '@/components/common/ChildSelector';
|
||||
import { useErrorMessage } from '@/components/common/ErrorMessage';
|
||||
import { formatErrorMessage } from '@/lib/utils/errorHandler';
|
||||
|
||||
interface ActivityData {
|
||||
activityType: string;
|
||||
@@ -83,7 +85,7 @@ function ActivityTrackPage() {
|
||||
const [recentActivities, setRecentActivities] = useState<Activity[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [activitiesLoading, setActivitiesLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { error, showError, clearError, hasError } = useErrorMessage();
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
|
||||
// Delete confirmation dialog
|
||||
@@ -131,19 +133,19 @@ function ActivityTrackPage() {
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedChild?.id) {
|
||||
setError('Please select a child');
|
||||
showError({ message: 'Please select a child', code: 'NO_CHILD_SELECTED' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Validation
|
||||
if (!activityType) {
|
||||
setError('Please select activity type');
|
||||
showError({ message: 'Please select activity type', code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
clearError();
|
||||
|
||||
const data: ActivityData = {
|
||||
activityType,
|
||||
@@ -167,7 +169,7 @@ function ActivityTrackPage() {
|
||||
await loadRecentActivities();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to save activity:', err);
|
||||
setError(err.response?.data?.message || 'Failed to save activity');
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -197,7 +199,7 @@ function ActivityTrackPage() {
|
||||
await loadRecentActivities();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to delete activity:', err);
|
||||
setError(err.response?.data?.message || 'Failed to delete activity');
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -306,9 +308,9 @@ function ActivityTrackPage() {
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
|
||||
{error}
|
||||
{hasError && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={clearError}>
|
||||
{formatErrorMessage(error)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
|
||||
@@ -48,6 +48,8 @@ import { childrenApi, Child } from '@/lib/api/children';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useLocalizedDate } from '@/hooks/useLocalizedDate';
|
||||
import { useTranslation } from '@/hooks/useTranslation';
|
||||
import { useErrorMessage } from '@/components/common/ErrorMessage';
|
||||
import { formatErrorMessage } from '@/lib/utils/errorHandler';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import { fetchChildren, selectChild, selectSelectedChild, childrenSelectors } from '@/store/slices/childrenSlice';
|
||||
import { AppDispatch, RootState } from '@/store/store';
|
||||
@@ -90,7 +92,7 @@ export default function DiaperTrackPage() {
|
||||
const [recentDiapers, setRecentDiapers] = useState<Activity[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [diapersLoading, setDiapersLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { error, showError, clearError, hasError } = useErrorMessage();
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
|
||||
// Delete confirmation dialog
|
||||
@@ -215,24 +217,24 @@ export default function DiaperTrackPage() {
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedChild?.id) {
|
||||
setError('Please select a child');
|
||||
showError({ message: 'Please select a child', code: 'NO_CHILD_SELECTED' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Validation
|
||||
if (!timestamp) {
|
||||
setError('Please enter timestamp');
|
||||
showError({ message: 'Please enter timestamp', code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (conditions.length === 0) {
|
||||
setError('Please select at least one condition');
|
||||
showError({ message: 'Please select at least one condition', code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
clearError();
|
||||
|
||||
const data: DiaperData = {
|
||||
diaperType,
|
||||
@@ -260,7 +262,7 @@ export default function DiaperTrackPage() {
|
||||
await loadRecentDiapers();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to save diaper:', err);
|
||||
setError(err.response?.data?.message || 'Failed to save diaper change');
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -292,7 +294,7 @@ export default function DiaperTrackPage() {
|
||||
await loadRecentDiapers();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to delete diaper:', err);
|
||||
setError(err.response?.data?.message || 'Failed to delete diaper change');
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -421,9 +423,9 @@ export default function DiaperTrackPage() {
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
|
||||
{error}
|
||||
{hasError && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={clearError}>
|
||||
{formatErrorMessage(error)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
|
||||
@@ -54,6 +54,8 @@ import { motion } from 'framer-motion';
|
||||
import { useLocalizedDate } from '@/hooks/useLocalizedDate';
|
||||
import { useTranslation } from '@/hooks/useTranslation';
|
||||
import { UnitInput } from '@/components/forms/UnitInput';
|
||||
import { useErrorMessage } from '@/components/common/ErrorMessage';
|
||||
import { formatErrorMessage } from '@/lib/utils/errorHandler';
|
||||
import { convertVolume, getUnitSymbol } from '@/lib/utils/unitConversion';
|
||||
import { MeasurementSystem } from '@/hooks/useLocale';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
@@ -106,7 +108,7 @@ function FeedingTrackPage() {
|
||||
const [recentFeedings, setRecentFeedings] = useState<Activity[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [feedingsLoading, setFeedingsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { error, showError, clearError, hasError } = useErrorMessage();
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
|
||||
// Delete confirmation dialog
|
||||
@@ -186,29 +188,29 @@ function FeedingTrackPage() {
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedChild?.id) {
|
||||
setError(t('common.selectChild'));
|
||||
showError({ message: t('common.selectChild'), code: 'NO_CHILD_SELECTED' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Validation
|
||||
if (feedingType === 'breast' && duration === 0 && timerSeconds === 0) {
|
||||
setError(t('feeding.validation.durationRequired'));
|
||||
showError({ message: t('feeding.validation.durationRequired'), code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (feedingType === 'bottle' && !amount) {
|
||||
setError(t('feeding.validation.amountRequired'));
|
||||
showError({ message: t('feeding.validation.amountRequired'), code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (feedingType === 'solid' && !foodDescription) {
|
||||
setError(t('feeding.validation.foodRequired'));
|
||||
showError({ message: t('feeding.validation.foodRequired'), code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
clearError();
|
||||
|
||||
const data: FeedingData = {
|
||||
feedingType,
|
||||
@@ -241,7 +243,7 @@ function FeedingTrackPage() {
|
||||
await loadRecentFeedings();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to save feeding:', err);
|
||||
setError(err.response?.data?.message || t('feeding.error.saveFailed'));
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -276,7 +278,7 @@ function FeedingTrackPage() {
|
||||
await loadRecentFeedings();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to delete feeding:', err);
|
||||
setError(err.response?.data?.message || t('feeding.error.deleteFailed'));
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -398,9 +400,9 @@ function FeedingTrackPage() {
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
|
||||
{error}
|
||||
{hasError && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={clearError}>
|
||||
{formatErrorMessage(error)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
|
||||
@@ -50,6 +50,8 @@ import { fetchChildren, selectChild, selectSelectedChild, childrenSelectors } fr
|
||||
import { AppDispatch, RootState } from '@/store/store';
|
||||
import ChildSelector from '@/components/common/ChildSelector';
|
||||
import { UnitInput } from '@/components/forms/UnitInput';
|
||||
import { useErrorMessage } from '@/components/common/ErrorMessage';
|
||||
import { formatErrorMessage } from '@/lib/utils/errorHandler';
|
||||
|
||||
interface GrowthData {
|
||||
weight?: number; // in kg
|
||||
@@ -84,7 +86,7 @@ function GrowthTrackPage() {
|
||||
const [recentGrowth, setRecentGrowth] = useState<Activity[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [growthLoading, setGrowthLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { error, showError, clearError, hasError } = useErrorMessage();
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
|
||||
// Delete confirmation dialog
|
||||
@@ -132,31 +134,31 @@ function GrowthTrackPage() {
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedChild?.id) {
|
||||
setError(t('common.selectChild'));
|
||||
showError({ message: t('common.selectChild'), code: 'NO_CHILD_SELECTED' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Validation
|
||||
if (measurementType === 'weight' && weight === 0) {
|
||||
setError('Please enter weight');
|
||||
showError({ message: 'Please enter weight', code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
if (measurementType === 'height' && height === 0) {
|
||||
setError('Please enter height');
|
||||
showError({ message: 'Please enter height', code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
if (measurementType === 'head' && headCircumference === 0) {
|
||||
setError('Please enter head circumference');
|
||||
showError({ message: 'Please enter head circumference', code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
if (measurementType === 'all' && (weight === 0 || height === 0 || headCircumference === 0)) {
|
||||
setError('Please enter all measurements');
|
||||
showError({ message: 'Please enter all measurements', code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
clearError();
|
||||
|
||||
const data: GrowthData = {
|
||||
measurementType,
|
||||
@@ -181,7 +183,7 @@ function GrowthTrackPage() {
|
||||
await loadRecentGrowth();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to save growth:', err);
|
||||
setError(err.response?.data?.message || 'Failed to save growth measurement');
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -212,7 +214,7 @@ function GrowthTrackPage() {
|
||||
await loadRecentGrowth();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to delete growth:', err);
|
||||
setError(err.response?.data?.message || 'Failed to delete growth measurement');
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -324,9 +326,9 @@ function GrowthTrackPage() {
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
|
||||
{error}
|
||||
{hasError && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={clearError}>
|
||||
{formatErrorMessage(error)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
|
||||
@@ -53,6 +53,8 @@ import { useTranslation } from '@/hooks/useTranslation';
|
||||
import { UnitInput } from '@/components/forms/UnitInput';
|
||||
import { convertVolume, convertTemperature } from '@/lib/utils/unitConversion';
|
||||
import { MeasurementSystem } from '@/hooks/useLocale';
|
||||
import { useErrorMessage } from '@/components/common/ErrorMessage';
|
||||
import { formatErrorMessage } from '@/lib/utils/errorHandler';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import { fetchChildren, selectChild, selectSelectedChild, childrenSelectors } from '@/store/slices/childrenSlice';
|
||||
import { AppDispatch, RootState } from '@/store/store';
|
||||
@@ -121,7 +123,7 @@ function MedicalTrackPage() {
|
||||
const [recentActivities, setRecentActivities] = useState<Activity[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [activitiesLoading, setActivitiesLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { error, showError, clearError, hasError } = useErrorMessage();
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
|
||||
// Delete confirmation dialog
|
||||
@@ -184,36 +186,36 @@ function MedicalTrackPage() {
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedChild?.id) {
|
||||
setError(t('common.selectChild'));
|
||||
showError({ message: t('common.selectChild'), code: 'NO_CHILD_SELECTED' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Validation based on activity type
|
||||
if (activityType === 'medication') {
|
||||
if (!medicineName) {
|
||||
setError(t('health.medicineName.required'));
|
||||
showError({ message: t('health.medicineName.required'), code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
const dosageValue = unit === 'ml' ? dosage : dosageText;
|
||||
if (!dosageValue || (unit === 'ml' && dosage === 0) || (unit !== 'ml' && !dosageText)) {
|
||||
setError(t('health.dosage.required'));
|
||||
showError({ message: t('health.dosage.required'), code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
} else if (activityType === 'temperature') {
|
||||
if (temperature === 0) {
|
||||
setError('Please enter temperature');
|
||||
showError({ message: 'Please enter temperature', code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
} else if (activityType === 'doctor') {
|
||||
if (!visitType) {
|
||||
setError('Please select visit type');
|
||||
showError({ message: 'Please select visit type', code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
clearError();
|
||||
|
||||
let data: MedicationData | TemperatureData | DoctorVisitData;
|
||||
|
||||
@@ -253,7 +255,7 @@ function MedicalTrackPage() {
|
||||
await loadRecentActivities();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to save activity:', err);
|
||||
setError(err.response?.data?.message || 'Failed to save activity');
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -299,7 +301,7 @@ function MedicalTrackPage() {
|
||||
await loadRecentActivities();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to delete activity:', err);
|
||||
setError(err.response?.data?.message || 'Failed to delete activity');
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -446,9 +448,9 @@ function MedicalTrackPage() {
|
||||
/>
|
||||
</Box>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
|
||||
{error}
|
||||
{hasError && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={clearError}>
|
||||
{formatErrorMessage(error)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
|
||||
@@ -47,6 +47,8 @@ import { childrenApi, Child } from '@/lib/api/children';
|
||||
import { motion } from 'framer-motion';
|
||||
import { useLocalizedDate } from '@/hooks/useLocalizedDate';
|
||||
import { useTranslation } from '@/hooks/useTranslation';
|
||||
import { useErrorMessage } from '@/components/common/ErrorMessage';
|
||||
import { formatErrorMessage } from '@/lib/utils/errorHandler';
|
||||
import { useDispatch, useSelector } from 'react-redux';
|
||||
import { fetchChildren, selectChild, selectSelectedChild, childrenSelectors } from '@/store/slices/childrenSlice';
|
||||
import { AppDispatch, RootState } from '@/store/store';
|
||||
@@ -91,7 +93,7 @@ export default function SleepTrackPage() {
|
||||
const [recentSleeps, setRecentSleeps] = useState<Activity[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [sleepsLoading, setSleepsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { error, showError, clearError, hasError } = useErrorMessage();
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
|
||||
// Delete confirmation dialog
|
||||
@@ -181,18 +183,18 @@ export default function SleepTrackPage() {
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!selectedChild?.id) {
|
||||
setError('Please select a child');
|
||||
showError({ message: 'Please select a child', code: 'NO_CHILD_SELECTED' });
|
||||
return;
|
||||
}
|
||||
|
||||
// Validation
|
||||
if (!startTime) {
|
||||
setError('Please enter start time');
|
||||
showError({ message: 'Please enter start time', code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isOngoing && !endTime) {
|
||||
setError('Please enter end time or mark as ongoing');
|
||||
showError({ message: 'Please enter end time or mark as ongoing', code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -200,14 +202,14 @@ export default function SleepTrackPage() {
|
||||
const start = new Date(startTime);
|
||||
const end = new Date(endTime);
|
||||
if (end <= start) {
|
||||
setError('End time must be after start time');
|
||||
showError({ message: 'End time must be after start time', code: 'VALIDATION_ERROR' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
clearError();
|
||||
|
||||
const data: SleepData = {
|
||||
startTime,
|
||||
@@ -236,7 +238,7 @@ export default function SleepTrackPage() {
|
||||
await loadRecentSleeps();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to save sleep:', err);
|
||||
setError(err.response?.data?.message || 'Failed to save sleep');
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -268,7 +270,7 @@ export default function SleepTrackPage() {
|
||||
await loadRecentSleeps();
|
||||
} catch (err: any) {
|
||||
console.error('Failed to delete sleep:', err);
|
||||
setError(err.response?.data?.message || 'Failed to delete sleep');
|
||||
showError(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -380,9 +382,9 @@ export default function SleepTrackPage() {
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={() => setError(null)}>
|
||||
{error}
|
||||
{hasError && (
|
||||
<Alert severity="error" sx={{ mb: 3 }} onClose={clearError}>
|
||||
{formatErrorMessage(error)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ import {
|
||||
import { Child, CreateChildData } from '@/lib/api/children';
|
||||
import { useTranslation } from '@/hooks/useTranslation';
|
||||
import { PhotoUpload } from '@/components/common/PhotoUpload';
|
||||
import { useErrorMessage } from '@/components/common/ErrorMessage';
|
||||
import { formatErrorMessage } from '@/lib/utils/errorHandler';
|
||||
|
||||
interface ChildDialogProps {
|
||||
open: boolean;
|
||||
@@ -33,7 +35,7 @@ export function ChildDialog({ open, onClose, onSubmit, child, isLoading = false
|
||||
photoUrl: '',
|
||||
photoAlt: '',
|
||||
});
|
||||
const [error, setError] = useState<string>('');
|
||||
const { error, showError, clearError, hasError } = useErrorMessage();
|
||||
|
||||
useEffect(() => {
|
||||
if (child) {
|
||||
@@ -53,8 +55,8 @@ export function ChildDialog({ open, onClose, onSubmit, child, isLoading = false
|
||||
photoAlt: '',
|
||||
});
|
||||
}
|
||||
setError('');
|
||||
}, [child, open]);
|
||||
clearError();
|
||||
}, [child, open, clearError]);
|
||||
|
||||
const handleChange = (field: keyof CreateChildData) => (
|
||||
e: React.ChangeEvent<HTMLInputElement>
|
||||
@@ -63,15 +65,15 @@ export function ChildDialog({ open, onClose, onSubmit, child, isLoading = false
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setError('');
|
||||
clearError();
|
||||
|
||||
// Validation
|
||||
if (!formData.name.trim()) {
|
||||
setError(t('dialog.validation.nameRequired'));
|
||||
showError({ message: t('dialog.validation.nameRequired'), code: 'VALIDATION_NAME_REQUIRED' });
|
||||
return;
|
||||
}
|
||||
if (!formData.birthDate) {
|
||||
setError(t('dialog.validation.birthDateRequired'));
|
||||
showError({ message: t('dialog.validation.birthDateRequired'), code: 'VALIDATION_BIRTHDATE_REQUIRED' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -80,7 +82,7 @@ export function ChildDialog({ open, onClose, onSubmit, child, isLoading = false
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
if (selectedDate > today) {
|
||||
setError(t('dialog.validation.birthDateFuture'));
|
||||
showError({ message: t('dialog.validation.birthDateFuture'), code: 'VALIDATION_BIRTHDATE_FUTURE' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -88,7 +90,7 @@ export function ChildDialog({ open, onClose, onSubmit, child, isLoading = false
|
||||
await onSubmit(formData);
|
||||
onClose();
|
||||
} catch (err: any) {
|
||||
setError(err.message || t('errors.saveFailed'));
|
||||
showError(err);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -107,9 +109,9 @@ export function ChildDialog({ open, onClose, onSubmit, child, isLoading = false
|
||||
id="child-dialog-description"
|
||||
sx={{ pt: 2, display: 'flex', flexDirection: 'column', gap: 2 }}
|
||||
>
|
||||
{error && (
|
||||
<Alert severity="error" onClose={() => setError('')} role="alert">
|
||||
{error}
|
||||
{hasError && (
|
||||
<Alert severity="error" onClose={clearError} role="alert">
|
||||
{formatErrorMessage(error)}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
|
||||
142
maternal-web/components/common/ErrorMessage.tsx
Normal file
142
maternal-web/components/common/ErrorMessage.tsx
Normal file
@@ -0,0 +1,142 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
import { Alert, AlertTitle, Box } from '@mui/material';
|
||||
import { extractError } from '@/lib/utils/errorHandler';
|
||||
|
||||
export interface ErrorMessageProps {
|
||||
error: any;
|
||||
showErrorCode?: boolean;
|
||||
variant?: 'standard' | 'filled' | 'outlined';
|
||||
severity?: 'error' | 'warning';
|
||||
onClose?: () => void;
|
||||
sx?: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* ErrorMessage Component
|
||||
* Displays error messages inline (within forms, pages, etc.)
|
||||
* Preserves backend multilingual error messages
|
||||
*/
|
||||
export function ErrorMessage({
|
||||
error,
|
||||
showErrorCode = false,
|
||||
variant = 'standard',
|
||||
severity = 'error',
|
||||
onClose,
|
||||
sx,
|
||||
}: ErrorMessageProps) {
|
||||
if (!error) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const extracted = extractError(error);
|
||||
|
||||
return (
|
||||
<Box sx={{ mb: 2, ...sx }}>
|
||||
<Alert severity={severity} variant={variant} onClose={onClose}>
|
||||
{showErrorCode && extracted.code && (
|
||||
<AlertTitle sx={{ fontWeight: 600 }}>{extracted.code}</AlertTitle>
|
||||
)}
|
||||
{extracted.message}
|
||||
</Alert>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* FieldError Component
|
||||
* Displays field-specific error messages (for form fields)
|
||||
*/
|
||||
export interface FieldErrorProps {
|
||||
error: any;
|
||||
fieldName: string;
|
||||
sx?: any;
|
||||
}
|
||||
|
||||
export function FieldError({ error, fieldName, sx }: FieldErrorProps) {
|
||||
if (!error) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const extracted = extractError(error);
|
||||
|
||||
// Only show if this error is for the specific field
|
||||
if (extracted.field !== fieldName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ mt: 0.5, ...sx }}>
|
||||
<Alert severity="error" variant="outlined" sx={{ py: 0.5, px: 1 }}>
|
||||
{extracted.message}
|
||||
</Alert>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* ErrorList Component
|
||||
* Displays multiple errors in a list
|
||||
*/
|
||||
export interface ErrorListProps {
|
||||
errors: any[];
|
||||
showErrorCodes?: boolean;
|
||||
variant?: 'standard' | 'filled' | 'outlined';
|
||||
onClose?: () => void;
|
||||
sx?: any;
|
||||
}
|
||||
|
||||
export function ErrorList({
|
||||
errors,
|
||||
showErrorCodes = false,
|
||||
variant = 'standard',
|
||||
onClose,
|
||||
sx,
|
||||
}: ErrorListProps) {
|
||||
if (!errors || errors.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const extractedErrors = errors.map((err) => extractError(err));
|
||||
|
||||
return (
|
||||
<Box sx={{ mb: 2, ...sx }}>
|
||||
<Alert severity="error" variant={variant} onClose={onClose}>
|
||||
<AlertTitle sx={{ fontWeight: 600 }}>Multiple errors occurred:</AlertTitle>
|
||||
<ul style={{ margin: '8px 0 0 0', paddingLeft: '20px' }}>
|
||||
{extractedErrors.map((err, index) => (
|
||||
<li key={index} style={{ marginBottom: '4px' }}>
|
||||
{showErrorCodes && err.code && <strong>{err.code}: </strong>}
|
||||
{err.message}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Alert>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to manage error message state
|
||||
*/
|
||||
export function useErrorMessage() {
|
||||
const [error, setError] = React.useState<any>(null);
|
||||
|
||||
const showError = (err: any) => {
|
||||
setError(err);
|
||||
};
|
||||
|
||||
const clearError = () => {
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const hasError = error !== null;
|
||||
|
||||
return {
|
||||
error,
|
||||
showError,
|
||||
clearError,
|
||||
hasError,
|
||||
};
|
||||
}
|
||||
80
maternal-web/components/common/ErrorToast.tsx
Normal file
80
maternal-web/components/common/ErrorToast.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
import { Snackbar, Alert, AlertTitle } from '@mui/material';
|
||||
import { extractError } from '@/lib/utils/errorHandler';
|
||||
|
||||
export interface ErrorToastProps {
|
||||
error: any;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
autoHideDuration?: number;
|
||||
showErrorCode?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* ErrorToast Component
|
||||
* Displays error messages as a toast notification
|
||||
* Preserves backend multilingual error messages
|
||||
*/
|
||||
export function ErrorToast({
|
||||
error,
|
||||
open,
|
||||
onClose,
|
||||
autoHideDuration = 6000,
|
||||
showErrorCode = false,
|
||||
}: ErrorToastProps) {
|
||||
if (!error) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const extracted = extractError(error);
|
||||
|
||||
return (
|
||||
<Snackbar
|
||||
open={open}
|
||||
autoHideDuration={autoHideDuration}
|
||||
onClose={onClose}
|
||||
anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
|
||||
>
|
||||
<Alert onClose={onClose} severity="error" variant="filled" sx={{ width: '100%' }}>
|
||||
{showErrorCode && extracted.code && (
|
||||
<AlertTitle>{extracted.code}</AlertTitle>
|
||||
)}
|
||||
{extracted.message}
|
||||
</Alert>
|
||||
</Snackbar>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to manage error toast state
|
||||
*/
|
||||
export function useErrorToast() {
|
||||
const [error, setError] = React.useState<any>(null);
|
||||
const [open, setOpen] = React.useState(false);
|
||||
|
||||
const showError = (err: any) => {
|
||||
setError(err);
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const hideError = () => {
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleClose = (_event?: React.SyntheticEvent | Event, reason?: string) => {
|
||||
if (reason === 'clickaway') {
|
||||
return;
|
||||
}
|
||||
hideError();
|
||||
};
|
||||
|
||||
return {
|
||||
error,
|
||||
open,
|
||||
showError,
|
||||
hideError,
|
||||
handleClose,
|
||||
};
|
||||
}
|
||||
@@ -79,13 +79,16 @@ export function JoinFamilyDialog({
|
||||
<TextField
|
||||
label="Share Code"
|
||||
value={shareCode}
|
||||
onChange={(e) => setShareCode(e.target.value)}
|
||||
onChange={(e) => setShareCode(e.target.value.toUpperCase())}
|
||||
fullWidth
|
||||
required
|
||||
autoFocus
|
||||
disabled={isLoading}
|
||||
placeholder="Enter family share code"
|
||||
helperText="Ask a family member for their share code"
|
||||
placeholder="XXXX-XXXX"
|
||||
helperText="Share codes are automatically converted to uppercase"
|
||||
inputProps={{
|
||||
style: { textTransform: 'uppercase' },
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
</DialogContent>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import axios from 'axios';
|
||||
import { tokenStorage } from '@/lib/utils/tokenStorage';
|
||||
import { logError } from '@/lib/utils/errorHandler';
|
||||
|
||||
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3020';
|
||||
|
||||
@@ -25,12 +26,15 @@ apiClient.interceptors.request.use(
|
||||
}
|
||||
);
|
||||
|
||||
// Response interceptor to handle token refresh
|
||||
// Response interceptor to handle token refresh and error logging
|
||||
apiClient.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
const originalRequest = error.config;
|
||||
|
||||
// Log all API errors for debugging and error tracking
|
||||
logError(error, `API ${originalRequest?.method?.toUpperCase()} ${originalRequest?.url}`);
|
||||
|
||||
// Only handle token refresh on client side
|
||||
if (typeof window === 'undefined') {
|
||||
return Promise.reject(error);
|
||||
|
||||
@@ -4,6 +4,7 @@ import { createContext, useContext, useEffect, useState, ReactNode } from 'react
|
||||
import { useRouter } from 'next/navigation';
|
||||
import apiClient from '@/lib/api/client';
|
||||
import { tokenStorage } from '@/lib/utils/tokenStorage';
|
||||
import { handleError, formatErrorMessage } from '@/lib/utils/errorHandler';
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
@@ -214,8 +215,8 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
||||
|
||||
router.push('/');
|
||||
} catch (error: any) {
|
||||
console.error('Login failed:', error);
|
||||
throw new Error(error.response?.data?.message || 'Login failed');
|
||||
const errorMessage = handleError(error, 'AuthContext.login');
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -285,8 +286,8 @@ export const AuthProvider = ({ children }: { children: ReactNode }) => {
|
||||
// Redirect to onboarding
|
||||
router.push('/onboarding');
|
||||
} catch (error: any) {
|
||||
console.error('Registration failed:', error);
|
||||
throw new Error(error.response?.data?.message || error.message || 'Registration failed');
|
||||
const errorMessage = handleError(error, 'AuthContext.register');
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
267
maternal-web/lib/utils/errorHandler.ts
Normal file
267
maternal-web/lib/utils/errorHandler.ts
Normal file
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* Error Handler Utility
|
||||
* Provides centralized error handling with multilingual support
|
||||
* Preserves backend error messages which are already localized in 5 languages:
|
||||
* - English (en)
|
||||
* - Spanish (es)
|
||||
* - French (fr)
|
||||
* - Portuguese (pt)
|
||||
* - Chinese (zh)
|
||||
*/
|
||||
|
||||
export interface ErrorResponse {
|
||||
code: string;
|
||||
message: string;
|
||||
field?: string;
|
||||
details?: any;
|
||||
}
|
||||
|
||||
export interface ExtractedError {
|
||||
code: string;
|
||||
message: string;
|
||||
field?: string;
|
||||
details?: any;
|
||||
isBackendError: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract error information from various error types
|
||||
* Prioritizes backend error messages to preserve multilingual support
|
||||
*/
|
||||
export function extractError(error: any): ExtractedError {
|
||||
// Default error
|
||||
const defaultError: ExtractedError = {
|
||||
code: 'UNKNOWN_ERROR',
|
||||
message: 'An unexpected error occurred. Please try again.',
|
||||
isBackendError: false,
|
||||
};
|
||||
|
||||
// If no error, return default
|
||||
if (!error) {
|
||||
return defaultError;
|
||||
}
|
||||
|
||||
// Axios error response with backend error
|
||||
if (error.response?.data?.error) {
|
||||
const backendError = error.response.data.error;
|
||||
return {
|
||||
code: backendError.code || 'BACKEND_ERROR',
|
||||
message: backendError.message || defaultError.message,
|
||||
field: backendError.field,
|
||||
details: backendError.details,
|
||||
isBackendError: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Axios error response with message
|
||||
if (error.response?.data?.message) {
|
||||
return {
|
||||
code: error.response.data.code || 'BACKEND_ERROR',
|
||||
message: error.response.data.message,
|
||||
field: error.response.data.field,
|
||||
details: error.response.data.details,
|
||||
isBackendError: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Network errors
|
||||
if (error.code === 'ERR_NETWORK' || error.message === 'Network Error') {
|
||||
return {
|
||||
code: 'NETWORK_ERROR',
|
||||
message: 'Unable to connect to the server. Please check your internet connection.',
|
||||
isBackendError: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Timeout errors
|
||||
if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) {
|
||||
return {
|
||||
code: 'TIMEOUT_ERROR',
|
||||
message: 'Request timed out. Please try again.',
|
||||
isBackendError: false,
|
||||
};
|
||||
}
|
||||
|
||||
// HTTP status code errors
|
||||
if (error.response?.status) {
|
||||
const status = error.response.status;
|
||||
|
||||
if (status === 401) {
|
||||
return {
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'Your session has expired. Please log in again.',
|
||||
isBackendError: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (status === 403) {
|
||||
return {
|
||||
code: 'FORBIDDEN',
|
||||
message: 'You do not have permission to perform this action.',
|
||||
isBackendError: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (status === 404) {
|
||||
return {
|
||||
code: 'NOT_FOUND',
|
||||
message: 'The requested resource was not found.',
|
||||
isBackendError: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (status === 429) {
|
||||
return {
|
||||
code: 'RATE_LIMIT_EXCEEDED',
|
||||
message: 'Too many requests. Please try again later.',
|
||||
isBackendError: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (status >= 500) {
|
||||
return {
|
||||
code: 'SERVER_ERROR',
|
||||
message: 'A server error occurred. Please try again later.',
|
||||
isBackendError: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Generic error with message
|
||||
if (error.message) {
|
||||
return {
|
||||
code: error.code || 'ERROR',
|
||||
message: error.message,
|
||||
isBackendError: false,
|
||||
};
|
||||
}
|
||||
|
||||
// String error
|
||||
if (typeof error === 'string') {
|
||||
return {
|
||||
code: 'ERROR',
|
||||
message: error,
|
||||
isBackendError: false,
|
||||
};
|
||||
}
|
||||
|
||||
return defaultError;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format error message for display
|
||||
* Preserves backend messages (which are already localized)
|
||||
*/
|
||||
export function formatErrorMessage(error: any): string {
|
||||
const extracted = extractError(error);
|
||||
return extracted.message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user-friendly error message based on error code
|
||||
* Only used for client-side errors; backend errors use their own messages
|
||||
*/
|
||||
export function getUserFriendlyMessage(errorCode: string): string {
|
||||
const messages: Record<string, string> = {
|
||||
// Network errors
|
||||
NETWORK_ERROR: 'Unable to connect to the server. Please check your internet connection.',
|
||||
TIMEOUT_ERROR: 'Request timed out. Please try again.',
|
||||
|
||||
// Authentication errors
|
||||
UNAUTHORIZED: 'Your session has expired. Please log in again.',
|
||||
FORBIDDEN: 'You do not have permission to perform this action.',
|
||||
|
||||
// HTTP errors
|
||||
NOT_FOUND: 'The requested resource was not found.',
|
||||
RATE_LIMIT_EXCEEDED: 'Too many requests. Please try again later.',
|
||||
SERVER_ERROR: 'A server error occurred. Please try again later.',
|
||||
|
||||
// Generic errors
|
||||
UNKNOWN_ERROR: 'An unexpected error occurred. Please try again.',
|
||||
ERROR: 'An error occurred. Please try again.',
|
||||
};
|
||||
|
||||
return messages[errorCode] || messages.UNKNOWN_ERROR;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if error is a specific type
|
||||
*/
|
||||
export function isErrorType(error: any, errorCode: string): boolean {
|
||||
const extracted = extractError(error);
|
||||
return extracted.code === errorCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if error is a network error
|
||||
*/
|
||||
export function isNetworkError(error: any): boolean {
|
||||
return isErrorType(error, 'NETWORK_ERROR');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if error is an authentication error
|
||||
*/
|
||||
export function isAuthError(error: any): boolean {
|
||||
return isErrorType(error, 'UNAUTHORIZED') || isErrorType(error, 'AUTH_TOKEN_EXPIRED');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if error is a validation error
|
||||
*/
|
||||
export function isValidationError(error: any): boolean {
|
||||
const extracted = extractError(error);
|
||||
return extracted.code.startsWith('VALIDATION_') || extracted.field !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get field-specific error message
|
||||
*/
|
||||
export function getFieldError(error: any, fieldName: string): string | null {
|
||||
const extracted = extractError(error);
|
||||
|
||||
if (extracted.field === fieldName) {
|
||||
return extracted.message;
|
||||
}
|
||||
|
||||
if (extracted.details && typeof extracted.details === 'object') {
|
||||
return extracted.details[fieldName] || null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Log error for debugging (can be extended with error tracking service)
|
||||
*/
|
||||
export function logError(error: any, context?: string): void {
|
||||
const extracted = extractError(error);
|
||||
|
||||
console.error('[Error Handler]', {
|
||||
context,
|
||||
code: extracted.code,
|
||||
message: extracted.message,
|
||||
field: extracted.field,
|
||||
details: extracted.details,
|
||||
isBackendError: extracted.isBackendError,
|
||||
originalError: error,
|
||||
});
|
||||
|
||||
// TODO: Send to error tracking service (Sentry, LogRocket, etc.)
|
||||
// Example:
|
||||
// if (window.Sentry) {
|
||||
// window.Sentry.captureException(error, {
|
||||
// tags: { code: extracted.code },
|
||||
// contexts: { errorHandler: { context } },
|
||||
// });
|
||||
// }
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle error and return user-friendly message
|
||||
* Main function to use in catch blocks
|
||||
*/
|
||||
export function handleError(error: any, context?: string): string {
|
||||
logError(error, context);
|
||||
return formatErrorMessage(error);
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
47
maternal-web/update-tracking-errors.sh
Normal file
47
maternal-web/update-tracking-errors.sh
Normal file
@@ -0,0 +1,47 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Script to update all tracking forms to use new error handling
|
||||
|
||||
TRACKING_FILES=(
|
||||
"/root/maternal-app/maternal-web/app/track/feeding/page.tsx"
|
||||
"/root/maternal-app/maternal-web/app/track/sleep/page.tsx"
|
||||
"/root/maternal-app/maternal-web/app/track/diaper/page.tsx"
|
||||
"/root/maternal-app/maternal-web/app/track/medicine/page.tsx"
|
||||
"/root/maternal-app/maternal-web/app/track/growth/page.tsx"
|
||||
"/root/maternal-app/maternal-web/app/track/activity/page.tsx"
|
||||
)
|
||||
|
||||
for file in "${TRACKING_FILES[@]}"; do
|
||||
if [ -f "$file" ]; then
|
||||
echo "Updating $file..."
|
||||
|
||||
# 1. Add imports at the top (after existing imports)
|
||||
if ! grep -q "useErrorMessage" "$file"; then
|
||||
# Find the last import line and add after it
|
||||
sed -i '/^import.*from/a\import { useErrorMessage } from "@/components/common/ErrorMessage";\nimport { formatErrorMessage } from "@/lib/utils/errorHandler";' "$file" | head -1
|
||||
fi
|
||||
|
||||
# 2. Replace error state declaration
|
||||
sed -i 's/const \[error, setError\] = useState<string | null>(null);/const { error, showError, clearError, hasError } = useErrorMessage();/' "$file"
|
||||
|
||||
# 3. Replace setError('') with clearError()
|
||||
sed -i "s/setError('')/clearError()/g" "$file"
|
||||
sed -i 's/setError("")/clearError()/g' "$file"
|
||||
sed -i 's/setError(null)/clearError()/g' "$file"
|
||||
|
||||
# 4. Replace setError with showError for error messages
|
||||
sed -i 's/setError(\([^)]*\))/showError(\1)/g' "$file"
|
||||
|
||||
# 5. Replace error && with hasError &&
|
||||
sed -i 's/error &&/hasError \&\&/g' "$file"
|
||||
|
||||
# 6. Replace {error} display with {formatErrorMessage(error)}
|
||||
sed -i 's/{error}/{formatErrorMessage(error)}/g' "$file"
|
||||
|
||||
echo " ✓ Updated $file"
|
||||
else
|
||||
echo " ✗ File not found: $file"
|
||||
fi
|
||||
done
|
||||
|
||||
echo "Done updating tracking forms!"
|
||||
Reference in New Issue
Block a user