summaryrefslogtreecommitdiff
path: root/common/errors.go
blob: 62899c197cc7f553525dcf225a28c6bc23a30da4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package common

import (
	"errors"
	"fmt"
	"reflect"
)

// IsErrorOfType is a modified version of errors.Is, which loosen the check condition
func IsErrorOfType(err, target error) bool {
	if target == nil {
		return err == target
	}

	isComparable := reflect.TypeOf(target).Comparable()
	for {
		if isComparable && reflect.TypeOf(target) == reflect.TypeOf(err) {
			return true
		}
		if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {
			return true
		}
		// TODO: consider supporting target.Is(err). This would allow
		// user-definable predicates, but also may allow for coping with sloppy
		// APIs, thereby making it easier to get away with them.
		if err = errors.Unwrap(err); err == nil {
			return false
		}
	}
}

/*
Task errors.
*/

type RecoverableTaskError struct {
	err     error
	message string
}

func (e *RecoverableTaskError) Error() string {
	return fmt.Sprintf("%v: %v", e.message, e.err)
}

func (e *RecoverableTaskError) Unwrap() error {
	return e.err
}

func NewRecoverableTaskError(message string, err error) error {
	return &RecoverableTaskError{message: message, err: err}
}

type UnrecoverableTaskError struct {
	err     error
	message string
}

func (e *UnrecoverableTaskError) Error() string {
	return fmt.Sprintf("%v: %v", e.message, e.err)
}

func (e *UnrecoverableTaskError) Unwrap() error {
	return e.err
}

func NewUnrecoverableTaskError(message string, err error) error {
	return &UnrecoverableTaskError{message: message, err: err}
}