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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM