相信很多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里的代码,并且捕获所有异常。