-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
93 lines (75 loc) · 2.35 KB
/
errors.go
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package amboy
import (
"context"
"errors"
"fmt"
)
// EnqueueUniqueJob is a generic wrapper for adding jobs to queues
// (using the Put() method), but that ignores duplicate job errors.
func EnqueueUniqueJob(ctx context.Context, queue Queue, job Job) error {
err := queue.Put(ctx, job)
if IsDuplicateJobError(err) {
return nil
}
return err
}
type duplJobError struct {
msg string
}
func (e *duplJobError) Error() string { return e.msg }
// NewDuplicateJobError creates a new error object to represent a
// duplicate job error, for use by queue implementations.
func NewDuplicateJobError(msg string) error { return &duplJobError{msg: msg} }
// NewDuplicateJobErrorf creates a new error object to represent a
// duplicate job error with a formatted message, for use by queue
// implementations.
func NewDuplicateJobErrorf(msg string, args ...interface{}) error {
return NewDuplicateJobError(fmt.Sprintf(msg, args...))
}
// MakeDuplicateJobError constructs a duplicate job error from an
// existing error of any type, for use by queue implementations.
func MakeDuplicateJobError(err error) error {
if err == nil {
return nil
}
return NewDuplicateJobError(err.Error())
}
// IsDuplicateJobError tests an error object to see if it is a
// duplicate job error.
func IsDuplicateJobError(err error) bool {
if err == nil {
return false
}
var dje *duplJobError
return errors.As(err, &dje)
}
type jobNotDefinedError struct {
ID string `bson:"job_id" json:"job_id" yaml:"job_id"`
QueueID string `bson:"queue_id" json:"queue_id" yaml:"queue_id"`
}
func (e *jobNotDefinedError) Error() string {
return fmt.Sprintf("job %q not defined in queue %q", e.ID, e.QueueID)
}
// NewJobNotDefinedError produces an error that is detectable with
// IsJobNotDefinedError, and can be produced by Get methods of
// queues.
func NewJobNotDefinedError(q Queue, id string) error {
return MakeJobNotDefinedError(q.ID(), id)
}
// MakeJobNotDefinedError provides a less well typed constructor for a
// job-not-defined error.
func MakeJobNotDefinedError(queueID, jobID string) error {
return &jobNotDefinedError{
ID: jobID,
QueueID: queueID,
}
}
// IsJobNotDefinedError returns true if the error is a job-not-defined
// error, and false otherwise.
func IsJobNotDefinedError(err error) bool {
if err == nil {
return false
}
var jnde *jobNotDefinedError
return errors.As(err, &jnde)
}