Dark mode
Error Handling in React (จัดการข้อผิดพลาดใน React)
การจัดการข้อผิดพลาดเป็นส่วนสำคัญในการพัฒนาแอปพลิเคชันที่เสถียร เราจะมาดูวิธีการจัดการข้อผิดพลาดใน React แบบต่างๆ
Error Boundaries (ขอบเขตการจัดการข้อผิดพลาด)
Error Boundaries เป็นคอมโพเนนต์ React ที่จับข้อผิดพลาดในลูกๆ คอมโพเนนต์ได้
tsx
class ErrorBoundary
extends React.Component<{ children: ReactNode }, { hasError: boolean }>
{
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log error to service like Sentry
console.error(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
// วิธีใช้
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>;
Try/Catch with Async Code (จัดการข้อผิดพลาดในโค้ด Async)
tsx
const fetchData = async () => {
try {
const response = await fetch("https://api.example.com/data");
if (!response.ok) throw new Error("Network response was not ok");
return await response.json();
} catch (error) {
console.error("Fetch error:", error);
// Fallback data หรือจัดการ error ที่นี่
return { data: [] };
}
};
Global Error Handling (จัดการข้อผิดพลาดระดับแอปพลิเคชัน)
tsx
// ในไฟล์หลักของแอป
window.addEventListener("error", (event) => {
// ส่ง error ไปยังบริการติดตาม error
console.error("Global error:", event.error);
});
window.addEventListener("unhandledrejection", (event) => {
// จัดการ Promise ที่ไม่มีการ catch
console.error("Unhandled rejection:", event.reason);
});
หมายเหตุ
- ควรใช้ Error Boundaries สำหรับจัดการข้อผิดพลาดใน UI
- ใช้ try/catch สำหรับโค้ด async และ operations ที่อาจเกิดข้อผิดพลาด
- ใช้บริการติดตาม error เช่น Sentry หรือ Bugsnag สำหรับ production
- ทดสอบ error scenarios ด้วย
- แสดง UI fallback ที่เหมาะสมเมื่อเกิดข้อผิดพลาด