Lua

Lesson 06

pcall error handling

Wrap untrusted or plugin code with pcall and convert failures into typed results for the host app.

Good Code

src/plugin_runner.lua
local function run_plugin(plugin, review)
  -- pcall keeps plugin errors from unwinding the host process.
  local ok, result = pcall(plugin.review, review)
  if not ok then
    return nil, { code = "plugin_error", message = result }
  end

  return result
end

Bad Code

plugin_runner.lua
local function run_plugin(plugin, review)
  -- A plugin error escapes without host context.
  return plugin.review(review)
end

Review Notes

What to review

Good Code

The good version catches plugin failures and turns them into a structured error table. The host can log the plugin name, disable it, or show a controlled message.

Bad Code

The bad version calls plugin code directly. A plugin error escapes through the host path without enough context for recovery.

Takeaways

  • Lua host code should catch plugin failures at the boundary and return a result the caller can classify.