Introduce ErrorBoundary component for improved error handling

- Add `ErrorBoundary` component to handle rendering fallback UI during errors.
- Integrate `ErrorBoundary` into main layout and critical pages for global error handling.
- Create `useErrorHandler` hook to handle async errors consistently across components.
- Refactor `NewCustomerModal` and `CustomersPage` to leverage `useErrorHandler` for improved error management.
- Add a fallback dialog UI for user-friendly error reporting and resolution.
This commit is contained in:
2025-07-11 19:06:07 +02:00
parent 2a95efb75f
commit 18014ce9f0
4 changed files with 196 additions and 42 deletions

View File

@@ -24,6 +24,7 @@ import {ArrowRight} from "lucide-react";
import {NewCustomerModal} from "@/components/customers/modal/NewCustomerModal"; import {NewCustomerModal} from "@/components/customers/modal/NewCustomerModal";
import {Customer} from "@/services/customers/entities/customer"; import {Customer} from "@/services/customers/entities/customer";
import Link from "next/link"; import Link from "next/link";
import {useErrorHandler} from "@/components/error-boundary";
export default function CustomersPage() { export default function CustomersPage() {
const [customers, setCustomers] = useState<Customer[]>([]); const [customers, setCustomers] = useState<Customer[]>([]);
@@ -31,6 +32,7 @@ export default function CustomersPage() {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1); const [page, setPage] = useState(1);
const pageSize = 15; const pageSize = 15;
const handleError = useErrorHandler();
useEffect(() => { useEffect(() => {
setLoading(true); setLoading(true);
@@ -45,13 +47,13 @@ export default function CustomersPage() {
setCustomers(data); setCustomers(data);
}) })
.catch((error) => { .catch((error) => {
console.error('Error fetching customers:', error); handleError(error);
setCustomers([]); setCustomers([]);
}) })
.finally(() => { .finally(() => {
setLoading(false); setLoading(false);
}); });
}, []); }, [handleError]);
const filtered = useMemo(() => { const filtered = useMemo(() => {
if (customers.length === 0) return []; if (customers.length === 0) return [];

View File

@@ -9,6 +9,8 @@ import {DynamicBreadcrumb} from "@/components/dynamic-breadcrumb";
import {getServerSession} from "next-auth"; import {getServerSession} from "next-auth";
import LoginScreen from "@/components/login-screen"; import LoginScreen from "@/components/login-screen";
import {authOptions} from "@/lib/api/auth/authOptions"; import {authOptions} from "@/lib/api/auth/authOptions";
import {ErrorBoundary} from "@/components/error-boundary";
import {Toaster} from "sonner";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Internal | Rhein Software", title: "Internal | Rhein Software",
@@ -25,6 +27,7 @@ export default async function RootLayout({
return ( return (
<html lang="de" suppressHydrationWarning> <html lang="de" suppressHydrationWarning>
<body> <body>
<ErrorBoundary>
<ThemeProvider <ThemeProvider
attribute="class" attribute="class"
defaultTheme="system" defaultTheme="system"
@@ -54,13 +57,19 @@ export default async function RootLayout({
<DynamicBreadcrumb/> <DynamicBreadcrumb/>
</div> </div>
</header> </header>
<ErrorBoundary>
{children} {children}
</ErrorBoundary>
</SidebarInset> </SidebarInset>
</SidebarProvider> </SidebarProvider>
) : ( ) : (
<ErrorBoundary>
<LoginScreen/> <LoginScreen/>
</ErrorBoundary>
)} )}
<Toaster/>
</ThemeProvider> </ThemeProvider>
</ErrorBoundary>
</body> </body>
</html> </html>
); );

View File

@@ -13,6 +13,7 @@ import {Card, CardContent, CardHeader} from "@/components/ui/card";
import {CreateCustomerDto, NoteDto, PhoneNumberDto} from "@/services/customers/dtos/createCustomer.dto"; import {CreateCustomerDto, NoteDto, PhoneNumberDto} from "@/services/customers/dtos/createCustomer.dto";
import {addCustomer} from "@/services/customers/usecases/addCustomer"; import {addCustomer} from "@/services/customers/usecases/addCustomer";
import {validateCustomer} from "@/services/customers/usecases/validateCustomer"; import {validateCustomer} from "@/services/customers/usecases/validateCustomer";
import {useErrorHandler} from "@/components/error-boundary";
export function NewCustomerModal() { export function NewCustomerModal() {
const [step, setStep] = useState(1); const [step, setStep] = useState(1);
@@ -28,6 +29,7 @@ export function NewCustomerModal() {
const [matches, setMatches] = useState<CustomerMatch[]>([]); const [matches, setMatches] = useState<CustomerMatch[]>([]);
const [showDetailModal, setShowDetailModal] = useState(false); const [showDetailModal, setShowDetailModal] = useState(false);
const [selectedCustomer] = useState<CustomerMatch | null>(null); const [selectedCustomer] = useState<CustomerMatch | null>(null);
const handleError = useErrorHandler();
type CustomerMatch = { type CustomerMatch = {
id: string; id: string;
@@ -52,15 +54,19 @@ export function NewCustomerModal() {
const result = await validateCustomer({email, companyName, street, zip, city}); const result = await validateCustomer({email, companyName, street, zip, city});
setMatches(result); setMatches(result);
} catch (err) { } catch (err) {
console.error("Validation failed", err); handleError(err);
} }
}; };
const handleSubmit = async () => { const handleSubmit = async () => {
if (!email || !name || !companyName || !street || !zip || !city) return; if (!email || !name || !companyName || !street || !zip || !city) return;
try {
const payload: CreateCustomerDto = {email, name, companyName, street, zip, city, phoneNumbers, notes}; const payload: CreateCustomerDto = {email, name, companyName, street, zip, city, phoneNumbers, notes};
await addCustomer(payload); await addCustomer(payload);
location.reload(); location.reload();
} catch (err) {
handleError(err);
}
}; };
const renderFormInput = ( const renderFormInput = (

View File

@@ -0,0 +1,137 @@
"use client";
import React from "react";
import { showError } from "@/lib/ui/showError";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
errorInfo: React.ErrorInfo | null;
}
interface ErrorBoundaryProps {
children: React.ReactNode;
fallback?: React.ComponentType<{ error: Error; reset: () => void }>;
}
export class ErrorBoundary extends React.Component<
ErrorBoundaryProps,
ErrorBoundaryState
> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
};
}
static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
return {
hasError: true,
error,
};
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error("ErrorBoundary caught an error:", error, errorInfo);
this.setState({
error,
errorInfo,
});
// Show error toast
showError(error);
}
handleReset = () => {
this.setState({
hasError: false,
error: null,
errorInfo: null,
});
};
render() {
if (this.state.hasError) {
if (this.props.fallback) {
const FallbackComponent = this.props.fallback;
return (
<FallbackComponent
error={this.state.error!}
reset={this.handleReset}
/>
);
}
return (
<ErrorDialog
error={this.state.error}
onReset={this.handleReset}
open={true}
/>
);
}
return this.props.children;
}
}
interface ErrorDialogProps {
error: Error | null;
onReset: () => void;
open: boolean;
}
function ErrorDialog({ error, onReset, open }: ErrorDialogProps) {
return (
<Dialog open={open} onOpenChange={() => {}}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Ein Fehler ist aufgetreten</DialogTitle>
<DialogDescription>
Es ist ein unerwarteter Fehler aufgetreten. Bitte versuchen Sie es erneut.
</DialogDescription>
</DialogHeader>
{error && (
<div className="mt-4 p-4 bg-red-50 dark:bg-red-900/20 rounded-md">
<p className="text-sm text-red-800 dark:text-red-200 font-mono">
{error.message}
</p>
</div>
)}
<DialogFooter className="flex gap-2">
<Button variant="outline" onClick={() => window.location.reload()}>
Seite neu laden
</Button>
<Button onClick={onReset}>
Erneut versuchen
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
// Hook for handling async errors
export function useErrorHandler() {
const handleError = React.useCallback((error: unknown) => {
console.error("Async error caught:", error);
showError(error);
}, []);
return handleError;
}