0Pricing
Elixir & Phoenix: Scalable Backend Development · บทเรียน

การจัดการข้อผิดพลาดและการบันทึกล็อกแบบมีโครงสร้าง

นำกลยุทธ์การจัดการข้อผิดพลาดที่รัดกุมมาใช้ และเรียนรู้การบันทึกล็อกแบบมีโครงสร้างเพื่อการดีบักและการตรวจติดตามที่มีประสิทธิภาพ

การจัดการข้อผิดพลาดและการบันทึกล็อกแบบมีโครงสร้าง เป็นบทเรียน Elixir & Phoenix: Scalable Backend Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Elixir & Phoenix: Scalable Backend Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Elixir & Phoenix: Scalable Backend Development มีบทเรียนทั้งหมด 4 บทเรียน

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

Why Error Handling Matters

In any application, things can go wrong. Users might input incorrect data, external services could fail, or files might not exist.

Error handling is about anticipating these issues and designing your application to respond gracefully, preventing crashes and ensuring a smooth user experience.

Elixir's 'Let It Crash' Philosophy

Elixir, built on the Erlang VM, embraces a unique approach called 'Let It Crash'. Instead of trying to prevent every possible error, Elixir processes are designed to be isolated.

If a process crashes, a supervisor can detect it and restart it, ensuring high availability. However, this primarily applies to process-level failures. For expected functional outcomes, a different pattern is used.

Tuples: {:ok, value} or {:error, reason}

For operations that might succeed or fail predictably, Elixir often uses a pattern of returning tuples: {:ok, result} for success and {:error, reason} for failure.

This makes the outcome explicit and avoids exceptions for expected scenarios, leading to clearer code.

defmodule AccountService do
  def withdraw(balance, amount) when amount > 0 and balance >= amount do
    {:ok, balance - amount}
  end

  def withdraw(balance, amount) when amount <= 0 do
    {:error, :invalid_amount}
  end

  def withdraw(balance, amount) when balance < amount do
    {:error, :insufficient_funds}
  end
end

IO.puts "Withdrawal 1: #{inspect AccountService.withdraw(100, 50)}"
IO.puts "Withdrawal 2: #{inspect AccountService.withdraw(100, 150)}"
IO.puts "Withdrawal 3: #{inspect AccountService.withdraw(100, 0)}"

Handling Results with `case`

Once a function returns an {:ok, ...} or {:error, ...} tuple, you can use Elixir's powerful pattern matching with a case statement to handle both outcomes explicitly.

This makes your error handling paths very clear and readable.

defmodule PaymentProcessor do
  def process_payment(amount, account_balance) do
    case AccountService.withdraw(account_balance, amount) do
      {:ok, new_balance} ->
        IO.puts "Payment successful! New balance: #{new_balance}"
        {:ok, new_balance}
      {:error, :insufficient_funds} ->
        IO.puts "Payment failed: Insufficient funds."
        {:error, :payment_failed}
      {:error, reason} ->
        IO.puts "Payment failed: Unknown reason #{reason}."
        {:error, :payment_failed}
    end
  end
end

# Assuming AccountService from previous scene is available
# Example usage:
PaymentProcessor.process_payment(30, 100)
PaymentProcessor.process_payment(120, 100)

The Power of `with` for Chaining

When you have multiple operations that might return {:error, ...} tuples and depend on the success of previous steps, the with special form is incredibly useful.

It allows you to chain these operations, and if any step returns an {:error, ...}, the with block immediately stops and returns that error, simplifying complex flows.

defmodule OrderProcessor do
  def process_order(user_id, item_id, quantity) do
    with {:ok, user} <- get_user(user_id),
         {:ok, item} <- get_item(item_id),
         {:ok, total_cost} <- calculate_cost(item, quantity),
         {:ok, _} <- deduct_funds(user, total_cost) do
      {:ok, "Order processed successfully for user #{user.name}"}
    else
      {:error, reason} -> {:error, reason}
    end
  end

  defp get_user(1), do: {:ok, %{name: "Alice"}}
  defp get_user(_), do: {:error, :user_not_found}

  defp get_item(101), do: {:ok, %{price: 20}}
  defp get_item(_), do: {:error, :item_not_found}

  defp calculate_cost(%{price: p}, q), do: {:ok, p * q}

  defp deduct_funds(%{name: "Alice"}, 40), do: {:ok, :deducted}
  defp deduct_funds(_, _), do: {:error, :payment_failed}
end

IO.puts "Processing good order: #{inspect OrderProcessor.process_order(1, 101, 2)}"
IO.puts "Processing bad order (item): #{inspect OrderProcessor.process_order(1, 999, 1)}"

Beyond Basic Logs: Structured Logging

Traditional logs often look like plain text messages, which are hard for machines to parse and query. Structured logging addresses this by outputting logs in a consistent, machine-readable format, usually JSON.

This makes it much easier to filter, analyze, and visualize your log data using tools like Kibana or Splunk, providing deeper insights into your application's behavior.

Your Go-To: The `Logger` Module

Elixir comes with a powerful built-in logging facility: the Logger module. It allows you to emit log messages at different severity levels, such as :debug, :info, :warn, and :error.

By default, Logger prints to the console, but it's highly configurable to send logs to files, external services, or other destinations.

defmodule MyApp do
  require Logger

  def start_process(id) do
    Logger.info "Starting process with ID: #{id}"
    # ... some work ...
    if id == 101 do
      Logger.warn "Process #{id} encountered a minor issue."
    else
      Logger.debug "Process #{id} completed successfully."
    end
  end

  def critical_error(message) do
    Logger.error "Critical error detected: #{message}"
  end
end

MyApp.start_process(100)
MyApp.start_process(101)
MyApp.critical_error("Database connection lost")

Contextual Logs with Metadata

One of the best features of Logger for structured logging is the ability to easily add metadata (extra key-value pairs) to your log messages.

This metadata provides crucial context, like a user_id, request_id, or specific parameters, making it much easier to trace issues and understand what happened during an event.

defmodule WebRequestLogger do
  require Logger

  def log_request(method, path, user_id, duration_ms) do
    Logger.info "Request processed",
      method: method,
      path: path,
      user_id: user_id,
      duration: "#{duration_ms}ms"
  end

  def log_error(error_message, user_id, request_id) do
    Logger.error error_message,
      user_id: user_id,
      request_id: request_id,
      component: :api_handler
  end
end

WebRequestLogger.log_request("GET", "/users/1", 123, 55)
WebRequestLogger.log_error("Invalid API key", 456, "abc-123")

Controlling Log Output with Levels

Each log message has a level (debug, info, warn, error, critical). You can configure your Elixir application's Logger to only output messages at or above a certain level.

For example, in a production environment, you might set the level to :info to avoid excessive :debug logs, while in development, you might set it to :debug for full visibility.

  • :debug: Detailed information, useful for debugging.
  • :info: General operational messages.
  • :warn: Potentially harmful situations.
  • :error: Error events that might still allow the application to continue.
  • :critical: Severe error events that likely cause an application to abort.

Check Your Understanding

Which of these are benefits of using structured logging in Elixir applications?

Lesson Summary: Robustness & Insight

In this lesson, you've learned to build more robust Elixir applications and gain better insights into their behavior:

  • Understood Elixir's approach to error handling with the 'Let It Crash' philosophy.
  • Mastered the use of {:ok, value} and {:error, reason} tuples for explicit functional error handling.
  • Utilized the with special form to elegantly chain operations that might fail.
  • Discovered the advantages of structured logging for machine-readable, searchable logs.
  • Learned to use Elixir's Logger module, including adding valuable metadata to your logs and configuring log levels.

These techniques are fundamental for developing production-ready, observable Elixir systems!

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

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

ใช่ — ข้อความเต็มของ “การจัดการข้อผิดพลาดและการบันทึกล็อกแบบมีโครงสร้าง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Elixir & Phoenix: Scalable Backend Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Elixir & Phoenix: Scalable Backend Development มีบทเรียนทั้งหมด 4 บทเรียน

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

นำกลยุทธ์การจัดการข้อผิดพลาดที่รัดกุมมาใช้ และเรียนรู้การบันทึกล็อกแบบมีโครงสร้างเพื่อการดีบักและการตรวจติดตามที่มีประสิทธิภาพ คุณปฏิบัติ Elixir & Phoenix: Scalable Backend Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Elixir & Phoenix: Scalable Backend Development หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Elixir & Phoenix: Scalable Backend Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

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

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

ฉันเขียนและรันโค้ดในบทเรียน Elixir & Phoenix: Scalable Backend Development นี้ได้ไหม

ได้ บทเรียน Elixir & Phoenix: Scalable Backend Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. การวัดประสิทธิภาพและการทำโพรไฟล์ Elixir
  2. การตรวจติดตามด้วย Telemetry และเมตริก
  3. การจัดการข้อผิดพลาดและการบันทึกล็อกแบบมีโครงสร้าง
  4. การติดตามแบบกระจายด้วย OpenTelemetry
← กลับไปที่ Elixir & Phoenix: Scalable Backend Development