WebSockets & Realtime Systems Programming · บทเรียน

การส่งต่อและกู้คืนข้อผิดพลาดอย่างมีประสิทธิภาพ

พัฒนากลยุทธ์สำหรับจัดการข้อผิดพลาด การบันทึกข้อมูล และการลดการทำงานลงอย่างเหมาะสมในแอปพลิเคชัน WebSocket

บทเรียน 2 จาก 411 ขั้นตอน

การส่งต่อและกู้คืนข้อผิดพลาดอย่างมีประสิทธิภาพ เป็นบทเรียน WebSockets & Realtime Systems Programming ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน WebSockets & Realtime Systems Programming และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส WebSockets & Realtime Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Handling Realtime Errors

Building reliable realtime applications requires more than just handling disconnections. You need a solid strategy for dealing with errors that occur within your WebSocket communication.

Robust error handling ensures your application remains stable, provides a good user experience, and helps you diagnose issues quickly.

Different Error Types

Errors in WebSocket applications can come from various sources:

  • Protocol Errors: These are issues like malformed frames or invalid opcodes. Your WebSocket library usually handles these automatically.
  • Application Logic Errors: Bugs in your server or client code that cause unexpected behavior or crashes during message processing.
  • Network Errors: Problems like firewalls, proxy issues, or unstable internet connections, often leading to connection loss.

We'll focus on handling application and network-related errors effectively.

Server Error Handling

On the server, WebSocket libraries provide mechanisms to catch errors. For example, in Node.js with the popular ws library, both the server instance and individual client connections can emit 'error' events.

It's crucial to listen for these events to prevent your server from crashing and to log issues for debugging.

Server Error in Action

This Node.js example shows a simple WebSocket server that intentionally throws an error when a specific message is received. Notice how the wss.on('error') and ws.on('error') handlers catch it.

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  console.log('Client connected');

  ws.on('message', function incoming(message) {
    console.log('Received: %s', message);
    if (message.toString() === 'cause error') {
      // Simulate an application logic error
      try {
        throw new Error('Simulated application error!');
      } catch (e) {
        console.error('Caught application error:', e.message);
        // In a real app, you might send this error to the client
        ws.send(JSON.stringify({ type: 'error', message: e.message }));
      }
    } else {
      ws.send(`Echo: ${message}`);
    }
  });

  ws.on('error', (error) => {
    console.error('WebSocket connection error:', error.message);
  });

  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

wss.on('error', (error) => {
  console.error('WebSocket server error:', error.message);
});

console.log('WebSocket server started on port 8080');
// To run this example:
// 1. npm init -y
// 2. npm install ws
// 3. node server.js
// Then connect with a client and send 'cause error'

Client Error Handling

On the client side, the browser's native WebSocket object provides an onerror event. This event fires when errors occur during connection establishment, or at any point during the connection's lifetime.

It's important to note that onerror often precedes or accompanies a onclose event, indicating a problematic connection termination.

Client Error in Action

This HTML and JavaScript snippet demonstrates how to set up an onerror handler for a WebSocket client. Try running the server from the previous scene and then this client in your browser.

<!DOCTYPE html>
<html>
<head>
  <title>WebSocket Client Error Handling</title>
</head>
<body>
  <h1>Client Error Handler</h1>
  <p id="status">Connecting...</p>
  <script>
    const statusElement = document.getElementById('status');
    const ws = new WebSocket('ws://localhost:8080');

    ws.onopen = () => {
      statusElement.textContent = 'Connected! Try sending "cause error" from a different client.';
      console.log('WebSocket connected.');
      ws.send('Hello server!');
    };

    ws.onmessage = (event) => {
      console.log('Message from server:', event.data);
      statusElement.textContent = `Received: ${event.data}`;
    };

    ws.onerror = (error) => {
      // The error object itself might not contain detailed info
      // but it signals that an error occurred.
      statusElement.textContent = 'Error occurred! Check console.';
      console.error('WebSocket error event:', error);
    };

    ws.onclose = (event) => {
      statusElement.textContent = `Disconnected. Code: ${event.code}, Reason: ${event.reason}`;
      console.log('WebSocket disconnected:', event);
    };
  </script>
</body>
</html>

Propagating Custom Errors

Sometimes, errors aren't about the connection itself, but about your application's logic. For example, a user trying to access unauthorized data or submitting invalid input. In these cases, you need to explicitly send an error message.

It's best practice to structure these as standard messages (e.g., JSON) with a specific type or status to differentiate them from regular data.

Server Sending Custom Errors

Here's how a server can send a structured error message back to the client. The client then needs to parse and handle this specific message type to react appropriately.

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8081 }); // Using a different port

wss.on('connection', function connection(ws) {
  console.log('Client connected to custom error server');

  ws.on('message', function incoming(message) {
    const msgStr = message.toString();
    if (msgStr === 'fetch_sensitive_data') {
      // Simulate an authorization error
      const errorResponse = {
        type: 'error',
        code: 403,
        message: 'Access denied: You are not authorized for this data.'
      };
      ws.send(JSON.stringify(errorResponse));
    } else {
      ws.send(`Echo: ${msgStr}`);
    }
  });

  ws.on('error', (error) => console.error('Connection error:', error.message));
  ws.on('close', () => console.log('Client disconnected from custom error server'));
});

console.log('WebSocket server for custom errors started on port 8081');
// To run this example:
// 1. npm init -y
// 2. npm install ws
// 3. node server_custom_error.js
// Then connect a client and send 'fetch_sensitive_data'

Graceful Degradation

When a severe error occurs, instead of completely failing, your application can "gracefully degrade" its functionality. This means offering a reduced but still usable experience.

  • Partial Functionality: Disable features that rely on the problematic component, but keep others working.
  • Fallback Mechanisms: Use alternative (perhaps less real-time) methods, like refreshing data via traditional HTTP requests.
  • Inform User: Clearly communicate the issue and what functionality is affected, managing their expectations.

Error Strategy Check

Which of the following is an effective strategy for graceful degradation in a WebSocket application when a critical server-side error prevents real-time updates?

Error Handling Summary

You've learned that robust error handling in WebSocket applications involves understanding different error types, catching both server-side and client-side events, and explicitly propagating application-level errors.

Crucially, implementing graceful degradation ensures your application remains resilient and user-friendly even when things go wrong. Keep practicing these strategies to build more robust realtime systems!

เริ่มต้นได้ฟรี

เรียนรู้ WebSockets & Realtime Systems Programming ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
12
บทเรียน
47

คำถามที่พบบ่อย

บทเรียน “การส่งต่อและกู้คืนข้อผิดพลาดอย่างมีประสิทธิภาพ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การส่งต่อและกู้คืนข้อผิดพลาดอย่างมีประสิทธิภาพ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Realtime Systems Programming ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Realtime Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การส่งต่อและกู้คืนข้อผิดพลาดอย่างมีประสิทธิภาพ”

พัฒนากลยุทธ์สำหรับจัดการข้อผิดพลาด การบันทึกข้อมูล และการลดการทำงานลงอย่างเหมาะสมในแอปพลิเคชัน WebSocket คุณปฏิบัติ WebSockets & Realtime Systems Programming ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Realtime Systems Programming หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Realtime Systems Programming บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การส่งต่อและกู้คืนข้อผิดพลาดอย่างมีประสิทธิภาพ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Realtime Systems Programming นี้ได้ไหม

ได้ บทเรียน WebSockets & Realtime Systems Programming ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การจัดการการตัดการเชื่อมต่อและการเชื่อมต่อใหม่
  2. การส่งต่อและกู้คืนข้อผิดพลาดอย่างมีประสิทธิภาพ
  3. สัญญาณชีพและการคงการเชื่อมต่อ
  4. การรับรองข้อความและการรับประกันการส่ง
← กลับไปที่ WebSockets & Realtime Systems Programming