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

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.

主站蜘蛛池模板: 五华县| 建阳市| 三台县| 新郑市| 建宁县| 七台河市| 台南市| 永平县| 枣阳市| 缙云县| 延安市| 涟水县| 洪江市| 盐池县| 永定县| 扶风县| 沛县| 德庆县| 卓资县| 股票| 鹤山市| 汉沽区| 隆德县| 科技| 伊宁市| 五寨县| 安庆市| 桦甸市| 大石桥市| 肥东县| 滦平县| 香港 | 老河口市| 资兴市| 广饶县| 阿拉善右旗| 冷水江市| 灌南县| 惠来县| 石楼县| 衡东县|