1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
|
print("=== Lua Error Handling Example ===")
print("\n1. Basic Error Throwing")
function divide(a, b) if b == 0 then error("Division by zero") end return a / b end
print("\n2. pcall (Protected Call)")
local success, result = pcall(divide, 10, 2) if success then print("10 / 2 =", result) else print("Error:", result) end
local success, result = pcall(divide, 10, 0) if success then print("10 / 0 =", result) else print("Error:", result) end
local success, result = pcall(function() return divide(20, 4) end) print("20 / 4 =", result)
print("\n3. xpcall (Extended Protected Call)")
local function error_handler(err) return "Custom error handler: " .. err .. "\nStack trace: " .. debug.traceback() end
local success, result = xpcall(function() return divide(10, 0) end, error_handler)
if success then print("Result:", result) else print("Error with traceback:", result) end
print("\n4. Custom Error Handling")
function safe_call(func, ...) local args = {...} return xpcall(function() return func(unpack(args)) end, function(err) local trace = debug.traceback() return { success = false, error = err, traceback = trace, timestamp = os.time() } end) end
local success, result = safe_call(divide, 15, 3) if success then print("15 / 3 =", result) else print("Error:", result) end
local success, result = safe_call(divide, 10, 0) if success then print("Result:", result) else print("Error details:") print(" Success:", result.success) print(" Error:", result.error) print(" Timestamp:", os.date("%Y-%m-%d %H:%M:%S", result.timestamp)) local trace_lines = {} for line in string.gmatch(result.traceback, "[^\n]+") do table.insert(trace_lines, line) if #trace_lines >= 5 then break end end print(" Traceback (first 5 lines):") for _, line in ipairs(trace_lines) do print(" " .. line) end end
print("\n5. Error Objects and Messages")
function process_data(data) if type(data) ~= "table" then error({code = 1001, message = "Invalid data type", expected = "table", got = type(data)}) end if not data.id then error({code = 1002, message = "Missing required field", field = "id"}) end return "Data processed successfully: " .. data.id end
local success, result = pcall(process_data, "not a table") if not success then if type(result) == "table" then print("Structured error:") print(" Code:", result.code) print(" Message:", result.message) print(" Expected:", result.expected) print(" Got:", result.got) else print("Simple error:", result) end end
local success, result = pcall(process_data, {name = "test"}) if not success then if type(result) == "table" then print("Structured error:") print(" Code:", result.code) print(" Message:", result.message) print(" Field:", result.field) else print("Simple error:", result) end end
print("\n6. Assertions")
local function safe_convert_to_number(str) local num = tonumber(str) assert(num ~= nil, "Invalid number format: " .. str) return num end
local success, result = pcall(safe_convert_to_number, "123") print("Convert '123' to number:", result)
local success, result = pcall(safe_convert_to_number, "abc") print("Convert 'abc' to number failed:", result)
print("\n7. Practical Error Handling Scenarios")
local function load_config(file_path) local file, err = io.open(file_path, "r") if not file then error("Failed to open config file: " .. err) end local content = file:read("*a") file:close() local config, err = load(content, file_path, "t", {}) if not config then error("Failed to parse config file: " .. err) end local success, result = pcall(config) if not success then error("Failed to execute config: " .. result) end return result end
local success, result = safe_call(load_config, "non_existent_config.lua") if not success then print("Config loading failed:", result.error) end
local function simulate_network_request(url, timeout) local random_failure = math.random(1, 5) if random_failure == 1 then error("Network timeout after " .. timeout .. "ms") end return { status = 200, url = url, data = {message = "Success", timestamp = os.time()} } end
print("\nNetwork request simulation:") for i = 1, 3 do local success, result = safe_call(simulate_network_request, "https://example.com/api", 5000) if success then print("Request " .. i .. " succeeded:", result.status) else print("Request " .. i .. " failed:", result.error) end end
print("\n8. Nested Error Handling")
local function outer_function() print("Entering outer_function") local success, result = pcall(function() print("Entering inner function") local data = nil data.field = "value" print("Exiting inner function") return "Success" end) if not success then print("Inner function error:", result) end print("Exiting outer_function") return "Outer success" end
local success, result = pcall(outer_function) print("Final result:", success and result or result)
print("\n9. Resource Cleanup and Error Handling")
local function process_with_resources() local resource = {name = "test_resource", opened = true} print("Resource opened:", resource.name) local success, result = xpcall(function() error("Error during resource processing") return "Processed successfully" end, function(err) resource.opened = false print("Resource cleaned up:", resource.name) return err end) return success, result end
local success, result = process_with_resources() print("Process result:", success and result or result)
print("\n=== End of Error Handling Examples ===")
|