-
Notifications
You must be signed in to change notification settings - Fork 0
/
error_new.go
44 lines (35 loc) · 904 Bytes
/
error_new.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
package httperror
import (
"context"
"fmt"
)
// ErrorOption is a function that modifies an error.
type ErrorOption func(error *Error)
// NewError creates a new error with the given message and status code.
func NewError(err interface{}, status int, options ...ErrorOption) error {
var result Error
result.status = status
if readErr, isErr := err.(error); isErr {
result.message = readErr.Error()
} else if readText, isText := err.(string); isText {
result.message = readText
} else {
result.message = fmt.Sprintf("%v", err)
}
for _, opt := range options {
opt(&result)
}
return result
}
// WithCode sets the code of the error.
func WithCode(code string) ErrorOption {
return func(result *Error) {
result.code = code
}
}
// WithContext sets the context of the error.
func WithContext(ctx context.Context) ErrorOption {
return func(result *Error) {
result.ctx = ctx
}
}