# HG changeset patch # User Matthew Wild # Date 1546174558 0 # Node ID 848fd204708ccc3dd840ab253148ee3fb94129df # Parent 0dbb285f903edca5e8db751578b4fecfb1808933 util.error: Add new util library for structured errors diff -r 0dbb285f903e -r 848fd204708c util/error.lua --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/util/error.lua Sun Dec 30 12:55:58 2018 +0000 @@ -0,0 +1,40 @@ +local error_mt = { __name = "error" }; + +function error_mt:__tostring() + return ("error<%s:%s:%s>"):format(self.type, self.condition, self.text); +end + +local function is_err(e) + return getmetatable(e) == error_mt; +end + +local function new(e, context, registry) + local template = (registry and registry[e]) or e or {}; + return setmetatable({ + type = template.type or "cancel"; + condition = template.condition or "undefined-condition"; + text = template.text; + + context = context or template.context or { _error_id = e }; + }, error_mt); +end + +local function coerce(ok, err, ...) + if ok or is_err(err) then + return ok, err, ...; + end + + local new_err = setmetatable({ + native = err; + + type = "cancel"; + condition = "undefined-condition"; + }, error_mt); + return ok, new_err, ...; +end + +return { + new = new; + coerce = coerce; + is_err = is_err; +}