From 4adfd7a5014469363df79b7a2263c07184f5999d Mon Sep 17 00:00:00 2001 From: mpeterv Date: Mon, 25 Jan 2016 14:53:18 +0300 Subject: [PATCH] Support table errors in socket.newtry/protect Instead of simply wrapping errors in a table in newtry and considering all tables exceptions in protect, add a metatable to exception wrapper and check that. This allows using protect with functions that may throw error objects. Additionally, assign __tostring metamethod to the exception metatable so that unhandled exceptions can be viewed normally. --- src/except.lua | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/except.lua b/src/except.lua index 4b98caf..2a11b04 100644 --- a/src/except.lua +++ b/src/except.lua @@ -28,6 +28,12 @@ local base = _G local _M = {} +local exception_metat = {} + +function exception_metat:__tostring() + return base.tostring(self[1]) +end + local function do_nothing() end function _M.newtry(finalizer) @@ -38,7 +44,7 @@ function _M.newtry(finalizer) return ... else base.pcall(finalizer) - base.error({err}) + base.error(base.setmetatable({err}, exception_metat)) end end end @@ -48,7 +54,7 @@ local function handle_pcall_returns(ok, ...) return ... else local err = ... - if base.type(err) == "table" then + if base.getmetatable(err) == exception_metat then return nil, err[1] else base.error(err, 0)