0Pricing
Erlang OTP: Distributed & Fault-Tolerant Systems Programming · 课时

健壮的错误处理

使用 try/catch、退出信号和退出捕获策略实现有针对性的错误处理,以优雅地管理故障。

健壮的错误处理 是 CoddyKit 上的免费 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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.

常见问题解答

「健壮的错误处理」课时是免费的吗?

是的 — 「健壮的错误处理」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 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 导师会在你学习这节课的过程中回答你的问题。

学习 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「健壮的错误处理」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课中编写并运行代码吗?

能。每节 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 链接与监视器详解
  2. 健壮的错误处理
  3. 面向崩溃优先进行设计
  4. “任其崩溃”理念
← 返回 Erlang OTP: Distributed & Fault-Tolerant Systems Programming