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
21import (
22	"errors"
23)
24
25type TemporaryErr interface {
26	Temporary() bool
27}
28
29// IsTemporaryOrUnspec is similar to IsTemporary except that it returns true
30// if error does not have a Temporary() method. Basically, it assumes that
31// errors are temporary by default compared to IsTemporary that assumes
32// errors are permanent by default.
33func IsTemporaryOrUnspec(err error) bool {
34	var temp TemporaryErr
35	if errors.As(err, &temp) {
36		return temp.Temporary()
37	}
38	return true
39}
40
41// IsTemporary returns true whether the passed error object
42// have a Temporary() method and it returns true.
43func IsTemporary(err error) bool {
44	var temp TemporaryErr
45	if errors.As(err, &temp) {
46		return temp.Temporary()
47	}
48	return false
49}
50
51type temporaryErr struct {
52	err  error
53	temp bool
54}
55
56func (t temporaryErr) Unwrap() error {
57	return t.err
58}
59
60func (t temporaryErr) Error() string {
61	return t.err.Error()
62}
63
64func (t temporaryErr) Temporary() bool {
65	return t.temp
66}
67
68// WithTemporary wraps the passed error object with the implementation of the
69// Temporary() method that will return the specified value.
70//
71// Original error value can be obtained using errors.Unwrap.
72func WithTemporary(err error, temporary bool) error {
73	return temporaryErr{err, temporary}
74}