在执行lua脚本时如何统一捕获异常

来源:互联网 发布:南昌网络教育 编辑:程序博客网 时间:2024/06/11 06:05

相信很多lua开发者都知道,在lua里面,可以使用pcall函数来捕获异常,但pcall只能捕获函数执行过程中抛出的异常,如果我想捕获整个脚本执行过程中的异常呢?方法也是有的,我们可以使用loadfile这个函数来实现,并且需要加多一个入口脚本。

业务脚本(hello_world.lua)

-- 使用error函数抛出一个异常error({code = 10001, msg = "发生错误了!"}) 

入口脚本(index.lua)

local cjson = require "cjson"local func = loadfile("/path/to/hello_world.lua")local status,err = pcall(func) -- 把整个脚本当作函数来执行if not status then    local code = err.code and tonumber(err.code) or 500    local msg = err.msg and tostring(err.msg) or "Unknown error occurred"    print(cjson.encode({code = code,msg = msg})) -- 输出{"code":10001,"msg":"发生错误了!"}end

有了入口脚本之后,我们执行的时候就直接执行index.lua,然后它会自己去执行hello_world.lua里的代码,并且捕获所有异常。

0 0
原创粉丝点击