lua以xpcall实现try/catch功能

复制代码

复制代码
-- 打印错误信息
local function __TRACKBACK__(errmsg)
    local track_text = debug.traceback(tostring(errmsg), 6);
    print("---------------------------------------- TRACKBACK ----------------------------------------");
    print(track_text, "LUA ERROR");
    print("---------------------------------------- TRACKBACK ----------------------------------------");
    local exception_text = "LUA EXCEPTION\n" .. track_text;
    return false;
end

--[[ 尝试调一个function 这个function可以带可变参数
如果被调用的函数有异常 返回false,退出此方法继续执行其他代码并打印出异常信息;]]
function trycall(func, ...)
    local args = { ... };
    return xpcall(function() func(unpack(args)) end, __TRACKBACK__);
end
--测试代码:

trycall(function(param)
      print("message "..param)
      print("message "..nil)
        end, "test trycall")
复制代码
复制代码

##输出结果如下:

>lua -e "io.stdout:setvbuf 'no'" "itertor_test.lua"
message test trycall
---------------------------------------- TRACKBACK ----------------------------------------
itertor_test.lua:45: attempt to concatenate a nil value
stack traceback:
itertor_test.lua:43: in main chunk
[C]: ? LUA ERROR
---------------------------------------- TRACKBACK ----------------------------------------
>Exit code: 0

 

xpcall (f, err)

This function is similar to pcall,except that you can set a new error handler.

xpcall calls function f in protected mode,using err as the error handler.Any error inside f is not propagated;instead, xpcall catches the error,calls the err function with the original error object,and returns a status code.Its first result is the status code (a boolean),which is true if the call succeeds without errors.In this case, xpcall also returns all results from the call,after this first result.In case of any error,xpcall returns false plus the result from err.

posted @   云轩奕鹤  阅读(9866)  评论(1编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示