maddy

Fork https://github.com/foxcpp/maddy

git clone git://git.lin.moe/go/maddy.git

 1/*
 2Maddy Mail Server - Composable all-in-one email server.
 3Copyright © 2019-2020 Max Mazurov <fox.cpp@disroot.org>, Maddy Mail Server contributors
 4
 5This program is free software: you can redistribute it and/or modify
 6it under the terms of the GNU General Public License as published by
 7the Free Software Foundation, either version 3 of the License, or
 8(at your option) any later version.
 9
10This program is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with this program.  If not, see <https://www.gnu.org/licenses/>.
17*/
18
19package exterrors
20
21type fieldsErr interface {
22	Fields() map[string]interface{}
23}
24
25type unwrapper interface {
26	Unwrap() error
27}
28
29type fieldsWrap struct {
30	err    error
31	fields map[string]interface{}
32}
33
34func (fw fieldsWrap) Error() string {
35	return fw.err.Error()
36}
37
38func (fw fieldsWrap) Unwrap() error {
39	return fw.err
40}
41
42func (fw fieldsWrap) Fields() map[string]interface{} {
43	return fw.fields
44}
45
46func Fields(err error) map[string]interface{} {
47	fields := make(map[string]interface{}, 5)
48
49	for err != nil {
50		errFields, ok := err.(fieldsErr)
51		if ok {
52			for k, v := range errFields.Fields() {
53				// Outer errors override fields of the inner ones.
54				// Not the reverse.
55				if fields[k] != nil {
56					continue
57				}
58				fields[k] = v
59			}
60		}
61
62		unwrap, ok := err.(unwrapper)
63		if !ok {
64			break
65		}
66		err = unwrap.Unwrap()
67	}
68
69	return fields
70}
71
72func WithFields(err error, fields map[string]interface{}) error {
73	return fieldsWrap{err: err, fields: fields}
74}