Comparison

util/error.lua @ 10563:e8db377a2983

Merge 0.11->trunk
author Kim Alvefur <zash@zash.se>
date Tue, 24 Dec 2019 00:39:45 +0100
parent 10501:e8186aba1583
child 11050:51be24b16e8a
comparison
equal deleted inserted replaced
10562:670afc079f68 10563:e8db377a2983
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 or "");
5 end
6
7 local function is_err(e)
8 return getmetatable(e) == error_mt;
9 end
10
11 -- Do we want any more well-known fields?
12 -- Or could we just copy all fields from `e`?
13 -- Sometimes you want variable details in the `text`, how to handle that?
14 -- Translations?
15 -- Should the `type` be restricted to the stanza error types or free-form?
16 -- What to set `type` to for stream errors or SASL errors? Those don't have a 'type' attr.
17
18 local function new(e, context, registry)
19 local template = (registry and registry[e]) or e or {};
20 return setmetatable({
21 type = template.type or "cancel";
22 condition = template.condition or "undefined-condition";
23 text = template.text;
24 code = template.code;
25
26 context = context or template.context or { _error_id = e };
27 }, error_mt);
28 end
29
30 local function coerce(ok, err, ...)
31 if ok or is_err(err) then
32 return ok, err, ...;
33 end
34
35 local new_err = setmetatable({
36 native = err;
37
38 type = "cancel";
39 condition = "undefined-condition";
40 }, error_mt);
41 return ok, new_err, ...;
42 end
43
44 local function from_stanza(stanza, context)
45 local error_type, condition, text = stanza:get_error();
46 return setmetatable({
47 type = error_type or "cancel";
48 condition = condition or "undefined-condition";
49 text = text;
50
51 context = context or { stanza = stanza };
52 }, error_mt);
53 end
54
55 return {
56 new = new;
57 coerce = coerce;
58 is_err = is_err;
59 from_stanza = from_stanza;
60 }