-
Notifications
You must be signed in to change notification settings - Fork 2
/
error.go
52 lines (45 loc) · 947 Bytes
/
error.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
package gokit_realworld
import (
"errors"
"fmt"
)
// Application error codes.
const (
// Action cannot be performed.
EConflict = "conflict"
// Internal error.
EInternal = "internal"
// Entity does not exist.
ENotFound = "not_found"
// Too many API requests.
ERateLimit = "rate_limit"
// User ID validation failed.
EInvalidUserID = "invalid_user_id"
// Username validation failed.
EInvalidUsername = "invalid_username"
EIncorrectPassword = "incorrect_password"
)
type Error struct {
Code string
Err error
}
func (e Error) Error() string {
return fmt.Sprintf("%s: %v", e.Code, e.Err)
}
func (e Error) Unwrap() error {
return e.Err
}
// ErrorCode returns the code of the error, if available.
func ErrorCode(err error) string {
var e Error
if errors.As(err, &e) {
return e.Code
}
return ""
}
func InternalError(err error) error {
return Error{
Code: EInternal,
Err: fmt.Errorf("internal error: %w", err),
}
}