官术网_书友最值得收藏!

Handling errors with pcall, xpcall, and assert

By default, the Lua language uses its internal error function. If an error occurs, Lua will usually abort code execution and put the error message with trace back into the standard error output. You can override the standard behavior with the pcall and xpcall functions. The main difference between these two functions is that pcall will return the status code and error message as the second return value, and xpcall will use the user-defined error function.

This way you can catch nonfatal errors and emulate the try and catch block.

Getting ready

This recipe will show error handling on a simple function that can exit prematurely with the error message:

 local function f1(a, b)
  assert((a == 1), "The first parameter must be equal to 1")
  print(b)
  return a+1
end

How to do it…

Here's how you can catch a nonfatal error with pcall by emulating the try and catch block:

function try(fn, catch_fn)
  local status, msg = pcall(fn)
  if not status then
    catch_fn(msg)
  end
end

try(function()
  f1(2, 3) -- this will throw "an exception"
end, function(e)
  print('An exception occured:', e)
  error('Throw exception')
end)

The next recipe shows how to create your own specialized xpcall2 function that can handle input parameters for a function:

local function xpcall2(fn, ...)
  local arg = {...}
  return xpcall(
    -- function wrapper to pass function arguments
    function(...)
      return fn(unpack(arg))
    end,
    -- error function
    function(msg)
      return debug.traceback(msg, 3)
    end
  )
end

print(xpcall2(f1, 2, 'a'))

How it works…

The whole principle of the try and catch block emulation in Lua relies on the pcall function that catches the error message and pushes it into the catch block function.

The only weakness of this approach is that you can't get more information because you're handling errors outside of the scope of where the error occurred.

This issue can be solved with xpcall which handles error before stack unwinding so you can use the debug library to get more information about the error.

Xpcall2 works as a wrapper function that not only passes parameters into protected function calls, but also handles getting the trace back with the debug.traceback function and returns results or a status code with an error message.

主站蜘蛛池模板: 孟州市| 罗定市| 明水县| 万盛区| 竹山县| 连州市| 克山县| 西畴县| 河西区| 阜阳市| 昭觉县| 红桥区| 右玉县| 肥城市| 永平县| 德惠市| 确山县| 商水县| 隆安县| 阜新市| 太仓市| 宁国市| 宜昌市| 比如县| 新源县| 岫岩| 依兰县| 中阳县| 贺兰县| 石棉县| 洪江市| 天门市| 定襄县| 治县。| 上林县| 视频| 延津县| 两当县| 简阳市| 方正县| 富顺县|