zoukankan      html  css  js  c++  java
  • 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
    " .. 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.

  • 相关阅读:
    Spring Cloud Bus 消息总线介绍
    工商银行分布式服务 C10K 场景解决方案
    关于写好文章的3个心法和5点技巧
    混合云K8s容器化应用弹性伸缩实战
    云原生下的灰度体系建设
    被解救的代码
    【2020-10-22】我是否一个真正靠谱的人
    【2020-10-21】以谦虚与忍耐去期待豁然与贯通
    【2020-10-20】压力也是一种感受,用心体会
    【2020-10-19】不断试错的过程
  • 原文地址:https://www.cnblogs.com/jadeboy/p/3978661.html
Copyright © 2011-2022 走看看