lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


The caller of pcall is responsible for propagating the errors however it sees fit (by raising an exception with error(), passing the error object around, or local handling).  The Lua core and standard library rarely raise exceptions themselves-- most errors are signaled by return arguments.  As far as the message handler of xpcall, it's not an error handler as you call it, but apparently a way to expand or translate the exception object in flight which will eventually be returned to the caller of xpcall.

Given your recent posts, I think you'd gain from the Lua Gems chapter I wrote, "Exceptions in Lua".  It covers error handling, why using inline functions as a poor-man's scope less than ideal, exception safety (i.e. finalization), and scope managers.  There's even a footnote that declares hooking of scope exit as the last fundamental building block missing from Lua :)


On Fri, Jul 20, 2018 at 7:22 PM, Soni "They/Them" L. <fakedme@gmail.com> wrote:
I noticed there doesn't seem to be any way to propagate errors "caught" with pcall/xpcall/lua_pcall. Why is this the case?

Throwing an error from the error handler isn't an option, as Lua eats those, and calling error() isn't an option as Lua eats the backtrace in that case. It would be nice to see a return value used to indicate whether to "keep unwinding" or just eat the error.[1][2]

Nested pcalls with "keep unwinding" set would give access to the full backtrace to all pcalls. That is, if you have 3 propagating pcalls then 1 eating pcall, they'd all have their error handlers called before the error unwinds the stack. Returning a new error object would use the new error object for future error handler calls. Error handlers would be called in reverse order. Erroring in non-propagating error handlers would just, uh, so like there are 2 ways to do this: restart the error handling from the top of the stack, or restart from the erroring error handler. I'm not sure which one would be "more correct" but I'd probably go with the latter.

Other languages don't do this - they print errors as soon as their equivalent of error() is called.[3]

[1] https://www.lua.org/manual/5.3/manual.html#2.3

[2] https://www.lua.org/manual/5.3/manual.html#lua_pcall

[3] https://doc.rust-lang.org/std/panic/fn.set_hook.html