Erlang OTP: Distributed & Fault-Tolerant Systems Programming · บทเรียน

การจัดการข้อผิดพลาดอย่างแข็งแกร่ง

ใช้งานการจัดการข้อผิดพลาดอย่างเป็นระบบด้วย try/catch สัญญาณการสิ้นสุด และการดักจับการสิ้นสุด เพื่อจัดการความล้มเหลวอย่างเหมาะสม

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

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

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

Erlang's Error Philosophy

Erlang is renowned for its fault tolerance. This isn't achieved by preventing all errors, but by expecting them and designing systems that can recover gracefully. We embrace the idea of 'let it crash' where appropriate, allowing supervisors to handle failures.

Catching Internal Errors

For errors that occur within a single process, Erlang provides the try...catch construct. This is useful for handling expected, localized issues like invalid function arguments, file not found errors, or custom application-specific exceptions.

It works similarly to exception handling in other languages, but it's less common for handling failures between different processes.

`try...catch` in Action

Let's see try...catch in a simple calculation. If an error happens, we can catch it and provide a fallback or log it. Notice how we match on error:badarith for a division-by-zero.

-module(calculator).
-export([safe_divide/2]).

safe_divide(A, B) ->
    try A / B of
        Result -> {ok, Result}
    catch
        error:badarith ->
            {error, division_by_zero}
    end.

% To run in shell:
% calculator:safe_divide(10, 2).
% calculator:safe_divide(10, 0).

Matching Different Exceptions

Erlang's try...catch allows matching on different types of exceptions:

  • throw: For expected conditions, often used to jump out of deep function calls.
  • exit: When a process terminates (e.g., exit(Reason)).
  • error: For unexpected runtime issues (e.g., division by zero, undefined function calls).

Each type can be caught and handled differently.

-module(exception_matcher).
-export([test_catch/1]).

test_catch(Val) ->
    try
        case Val of
            throw_it -> throw(something_thrown);
            exit_it  -> exit(something_exited);
            error_it -> 1 / 0;
            _        -> "no error"
        end
    catch
        throw:something_thrown -> {caught, thrown};
        exit:something_exited  -> {caught, exited};
        error:badarith         -> {caught, error_badarith};
        _                      -> {caught, unknown}
    end.

% To run in shell:
% exception_matcher:test_catch(throw_it).
% exception_matcher:test_catch(exit_it).
% exception_matcher:test_catch(error_it).

Exit Signals: Erlang's Core

Beyond `try...catch` for internal errors, Erlang processes communicate their termination using exit signals. When a process dies (either gracefully or due to an error), it sends an exit signal to all processes it's linked to.

This mechanism is fundamental for building fault-tolerant systems in Erlang.

Links Propagate Exits

By default, if two processes are linked and one terminates with an exit signal (other than normal), the other linked process will also terminate with the same reason. This is Erlang's 'let it crash' philosophy in action.

This propagation allows supervisors to detect and restart entire sub-systems, ensuring failures don't leave lingering, inconsistent state.

Trapping Exits with `process_flag`

Sometimes, a process needs to handle the exit of a linked process instead of crashing itself. This is achieved by "trapping exits". A process can set its trap_exit flag to true.

When trap_exit is true, exit signals from linked processes are converted into messages that are sent to the trapping process's mailbox.

Handling a Linked Process Exit

This example shows a 'parent' process linking to a 'worker'. The parent sets trap_exit to true. When the worker crashes, the parent doesn't crash but receives an {'EXIT', Pid, Reason} message, which it can then process.

-module(exit_trap_demo).
-export([start/0, worker/0]).

start() ->
    ParentPid = self(),
    WorkerPid = spawn_link(fun() -> worker() end),
    process_flag(trap_exit, true), % Parent traps exits
    io:format("Parent (~p) linked to Worker (~p)~n", [ParentPid, WorkerPid]),
    receive
        {'EXIT', WorkerPid, Reason} ->
            io:format("Parent caught worker exit: ~p~n", [Reason]),
            {worker_died, Reason}
    after 5000 ->
        io:format("Parent timed out waiting for worker exit.~n"),
        timeout
    end.

worker() ->
    io:format("Worker (~p) starting...~n", [self()]),
    timer:sleep(1000), % Do some work
    exit(bad_calculation). % Worker crashes

% To run in shell:
% exit_trap_demo:start().

Choosing Your Strategy

When should you trap exits versus letting them crash?

  • Let it Crash (default): Use when a failure in one process means the whole component is compromised. Supervisors will handle the restart logic.
  • Trap Exits: Use when a process needs to clean up resources, log the event, or attempt recovery from a linked process's failure without itself dying. This is often used by supervisors themselves.

Quick Check

Consider a scenario where process_A is linked to process_B. process_B crashes with reason error_condition.

Robust Error Handling Summary

We've explored key Erlang error handling strategies:

  • try...catch for localized, internal exceptions within a single process.
  • Exit signals as the primary mechanism for inter-process failure notification via links.
  • Trapping exits using process_flag(trap_exit, true) to convert exit signals from linked processes into messages, allowing a process to react to a linked process's termination without crashing itself.

Understanding these mechanisms is crucial for building resilient, fault-tolerant Erlang systems.

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

เรียนรู้ Erlang ด้วย AI tutor — ฟรี

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

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

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

บทเรียน “การจัดการข้อผิดพลาดอย่างแข็งแกร่ง” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “การจัดการข้อผิดพลาดอย่างแข็งแกร่ง”

ใช้งานการจัดการข้อผิดพลาดอย่างเป็นระบบด้วย try/catch สัญญาณการสิ้นสุด และการดักจับการสิ้นสุด เพื่อจัดการความล้มเหลวอย่างเหมาะสม คุณปฏิบัติ Erlang OTP: Distributed & Fault-Tolerant Systems Programming ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Erlang OTP: Distributed & Fault-Tolerant Systems Programming หรือไม่

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

บทเรียน “การจัดการข้อผิดพลาดอย่างแข็งแกร่ง” ใช้เวลานานแค่ไหน

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

ฉันเขียนและรันโค้ดในบทเรียน Erlang OTP: Distributed & Fault-Tolerant Systems Programming นี้ได้ไหม

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

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

  1. อธิบายลิงก์และตัวตรวจสอบ
  2. การจัดการข้อผิดพลาดอย่างแข็งแกร่ง
  3. การออกแบบตามหลักล้มเหลวก่อน
  4. ปรัชญา Let-It-Crash
← กลับไปที่ Erlang OTP: Distributed & Fault-Tolerant Systems Programming