lua以xpcall实现try/catch功能

简介: -- 打印错误信息 local function __TRACKBACK__(errmsg) local track_text = debug.traceback(tostring(errmsg), 6); print("----------------------...
 
 
-- 打印错误信息
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.

倾城之链 | NICE LINKS DJI Mavic Air
目录
相关文章
|
6天前
|
存储 NoSQL 数据处理
Redis Lua脚本:赋予Redis更强大的逻辑与功能
Redis Lua脚本:赋予Redis更强大的逻辑与功能
|
应用服务中间件 PHP nginx
nginx+ngx_lua支持WAF防护功能
安装nginx+ngx_lua支持WAF防护功能 nginx lua模块淘宝开发的nginx第三方模块,它能将lua语言嵌入到nginx配置中,从而使用lua就极大增强了nginx的能力.
2053 0
|
tengine 负载均衡 应用服务中间件
|
应用服务中间件 网络安全 nginx
|
NoSQL Redis 数据库
阿里云Redis LUA脚本功能上线——轻量嵌入,极速扩展,业务轻松跨平台
阿里云Redis云数据库,全面支持LUA脚本功能,助力企业轻松迁移自建Redis数据库的业务逻辑,实现业务的跨平台复用,快速驱动业务上云。
8327 0
|
6天前
|
存储 NoSQL Redis
Redis的Lua脚本有什么作用?
Redis Lua脚本用于减少网络开销、实现原子操作及扩展指令集。它能合并操作降低网络延迟,保证原子性,替代不支持回滚的事务。通过脚本,代码复用率提高,且可自定义指令,如实现分布式锁,增强Redis功能和灵活性。
47 1
|
6天前
|
存储 NoSQL 关系型数据库
使用lua脚本操作redis
使用lua脚本操作redis
51 0
|
6天前
|
缓存 NoSQL Java
【Redis】5、Redis 的分布式锁、Lua 脚本保证 Redis 命令的原子性
【Redis】5、Redis 的分布式锁、Lua 脚本保证 Redis 命令的原子性
66 0