lua-users home
lua-l archive

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


On Wed, Sep 10, 2014 at 5:18 PM, Andrew Starks <andrew.starks@trms.com> wrote:
> I haven't settled on a standardized way to error and I need to. At work,
> we've been debating one of two general strategies:
>
>  - make an 'error' method that creates an error object, which can log the
> error, put in the boiler plate text, add the object's name, etc. Once
> created, it would throw the error.
>
>     obj:error(400, "You needed to foo the bar before plotzing.")
>
> The other option is somewhat similar, except that it would return `nil,
> error_msg`
>
>     return obj:error(405, "Eating babies is not permitted with these
> credentials.")
>
> In the first case, we would use `pcall` in spots where we wanted to protect
> the lua thread from crashing. However, we'd mostly try to adopt a style
> "crash early and often in your own thread and make a new thread, in order to
> try again." This is generally attractive, but I'm worried about sockets and
> C-libraries with resources... Of course, we use the `__gc` metamethod, so
> nothing bad will ever happen, during a crash...
>
> In the second case, we'd avoid pcall, except when calling standard library
> functions that contain elements of application input. Then, we'd always use
> pcall. When `nil, 'error'` is returned for calls that should never error,
> we'd use `assert`, just to bring a modicum of sanity.
>
> So, second option uses assert sparingly and tries to handle errors without
> bringing things down. First option crashes early and often.
>
> In practice, I find that it's hard to tell what is happening, especially in
> a coroutine, and especially if I use the `nil, error` approach. I generally
> like my errors to be loud and obvious and haven't had a ton of success with
> 'quietly moving on.'
>
>
> Soo..... what do smart people do?
>
> -Andrew

The idiom I've heard and used is that returning (nil, errmsg) is for
runtime errors, and error() is for programming errors. So e.g.:
return nil, "Failed to open file: access denied"
vs:
error("Invalid argument to method frobulate (expected number)")

-- 
Sent from my Game Boy.