Software /
code /
prosody
Comparison
util/error.lua @ 9746:848fd204708c
util.error: Add new util library for structured errors
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Sun, 30 Dec 2018 12:55:58 +0000 |
child | 9749:9361bd1b9c9b |
comparison
equal
deleted
inserted
replaced
9745:0dbb285f903e | 9746:848fd204708c |
---|---|
1 local error_mt = { __name = "error" }; | |
2 | |
3 function error_mt:__tostring() | |
4 return ("error<%s:%s:%s>"):format(self.type, self.condition, self.text); | |
5 end | |
6 | |
7 local function is_err(e) | |
8 return getmetatable(e) == error_mt; | |
9 end | |
10 | |
11 local function new(e, context, registry) | |
12 local template = (registry and registry[e]) or e or {}; | |
13 return setmetatable({ | |
14 type = template.type or "cancel"; | |
15 condition = template.condition or "undefined-condition"; | |
16 text = template.text; | |
17 | |
18 context = context or template.context or { _error_id = e }; | |
19 }, error_mt); | |
20 end | |
21 | |
22 local function coerce(ok, err, ...) | |
23 if ok or is_err(err) then | |
24 return ok, err, ...; | |
25 end | |
26 | |
27 local new_err = setmetatable({ | |
28 native = err; | |
29 | |
30 type = "cancel"; | |
31 condition = "undefined-condition"; | |
32 }, error_mt); | |
33 return ok, new_err, ...; | |
34 end | |
35 | |
36 return { | |
37 new = new; | |
38 coerce = coerce; | |
39 is_err = is_err; | |
40 } |