Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

การดำเนินการสคริปต์เมื่อเกิดข้อผิดพลาด (Error) ใน HTML

เหตุการณ์ onerror จะถูกกระตุ้นเมื่อเกิดข้อผิดพลาดใน HTML เช่น โหลดรูปภาพไม่สำเร็จ, สคริปต์ผิดพลาด, หรือทรัพยากรไม่พบ

ตัวอย่าง

ลองรันโค้ดต่อไปนี้เพื่อใช้งานแอตทริบิวต์เหตุการณ์ onerror:

<!DOCTYPE html>
<html>
<body>
  <img src="new.png" onerror="handleError(this)">
  <p>Alert would be visible, if the image isn't loaded correctly.</p>
  <script>
    function handleError(img) {
      alert("Image load unsuccessful.");
      img.src = "fallback.png"; // เปลี่ยนเป็นรูปสำรอง
      img.onerror = null; // ป้องกัน loop
    }
  </script>
</body>
</html>

องค์ประกอบที่รองรับ onerror

  • <img> - โหลดรูปไม่สำเร็จ
  • <script> - สคริปต์ผิดพลาด
  • <link> - โหลด stylesheet ไม่สำเร็จ
  • <audio>, <video> - โหลดสื่อไม่สำเร็จ
  • <iframe> - โหลด iframe ไม่สำเร็จ
  • window.onerror - Global error handler

ตัวอย่าง: Global Error Handler

<script>
window.onerror = function(message, source, lineno, colno, error) {
  console.log('Error:', message);
  console.log('Source:', source);
  console.log('Line:', lineno, 'Column:', colno);
  console.log('Error object:', error);
  
  // ส่งไป Error Tracking Service (Sentry, LogRocket, etc.)
  // return true; // ป้องกัน default browser handler
};
</script>

ตัวอย่าง: รูปภาพ Fallback

<img src="photo.jpg" 
     onerror="this.onerror=null; this.src='placeholder.png';" 
     alt="Description">

ตัวอย่าง: Video Fallback

<video controls>
  <source src="video.webm" type="video/webm" onerror="fallback(this)">
  <source src="video.mp4" type="video/mp4">
</video>

<script>
function fallback(source) {
  source.parentNode.removeChild(source);
  // เบราว์เซอร์จะลอง source ถัดไปอัตโนมัติ
}
</script>

onerror vs try/catch

  • onerror - จับข้อผิดพลาด Runtime (โหลดทรัพยากร, uncaught exceptions)
  • try/catch - จับข้อผิดพลาดในโค้ดที่เขียนไว้เฉพาะบล็อก

หมายเหตุ: ใน Production ควรใช้ Error Tracking Services (Sentry, LogRocket, Rollbar) แทน alert()