PageRenderTime 44ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/lua/ex/error.lua

https://code.google.com/p/lua-aux-lib/
Lua | 79 lines | 53 code | 13 blank | 13 comment | 5 complexity | 6c228a73d2bfdaa78df07b6f63c8bfd3 MD5 | raw file
  1. --[[
  2. Error handling patterns
  3. continue(ok,err) -> either re-raise the error pcall returned or continue
  4. finalize(f,finf) -> newf()
  5. protect(f,finf) -> newf()
  6. try(f,catchf)
  7. ]]
  8. local pcall,error=
  9. pcall,error
  10. local _G,M=_G,{}
  11. setfenv(1,M)
  12. --usage: try(function() ... end, function(e) ... error(e) end)
  13. function try(f, catch_f)
  14. local ok,err = pcall(f)
  15. if not ok then
  16. catch_f(err)
  17. end
  18. end
  19. -- eg. continue(after(pcall,finf)(f,args))
  20. function continue(ok,...)
  21. return not ok and error(...,0) or ...
  22. end
  23. -- note: the finalizer doesn't run protected: if it breaks, the result of f is lost
  24. function finalize(f,finf)
  25. local function helper(...)
  26. finf(...)
  27. return ...
  28. end
  29. return function(...)
  30. return continue(helper(pcall(f,...)))
  31. end
  32. end
  33. local function protect_helper(finf,ok,...)
  34. if finf ~= nil then
  35. finf(ok,...)
  36. end
  37. if ok then return ... else return nil,... end
  38. end
  39. -- stops error propagation, returning nil,errmsg instead. also calls a finalizer, if given.
  40. function protect(f,finf)
  41. return function(...)
  42. return protect_helper(finf,pcall(f,...))
  43. end
  44. end
  45. if _G.__UNITTESTING then
  46. local assert=_G.assert
  47. ret,err=protect(finalize(function(a,b) error('err') end, function(ok,...) assert(not ok) end))(1,2)
  48. assert(ret==nil)
  49. assert(#err>0)
  50. local finalized
  51. ret,err=protect(function()
  52. ok,ret=pcall(function() error('err') end)
  53. continue(ok,ret)
  54. end,
  55. function(ok,...)
  56. finalized=true
  57. assert(not ok)
  58. end
  59. )()
  60. assert(finalized)
  61. assert(ret==nil)
  62. assert(#err>0)
  63. end
  64. return M