1package errors
2
3import (
4 "encoding/json"
5 "fmt"
6)
7
8type XrpcError struct {
9 Tag string `json:"error"`
10 Message string `json:"message"`
11}
12
13func (x XrpcError) Error() string {
14 if x.Message != "" {
15 return fmt.Sprintf("%s: %s", x.Tag, x.Message)
16 }
17 return x.Tag
18}
19
20func NewXrpcError(opts ...ErrOpt) XrpcError {
21 x := XrpcError{}
22 for _, o := range opts {
23 o(&x)
24 }
25
26 return x
27}
28
29type ErrOpt = func(xerr *XrpcError)
30
31func WithTag(tag string) ErrOpt {
32 return func(xerr *XrpcError) {
33 xerr.Tag = tag
34 }
35}
36
37func WithMessage[S ~string](s S) ErrOpt {
38 return func(xerr *XrpcError) {
39 xerr.Message = string(s)
40 }
41}
42
43func WithError(e error) ErrOpt {
44 return func(xerr *XrpcError) {
45 xerr.Message = e.Error()
46 }
47}
48
49var MissingActorDidError = NewXrpcError(
50 WithTag("MissingActorDid"),
51 WithMessage("actor DID not supplied"),
52)
53
54var AuthError = func(err error) XrpcError {
55 return NewXrpcError(
56 WithTag("Auth"),
57 WithError(fmt.Errorf("signature verification failed: %w", err)),
58 )
59}
60
61var InvalidRepoError = func(r string) XrpcError {
62 return NewXrpcError(
63 WithTag("InvalidRepo"),
64 WithError(fmt.Errorf("supplied at-uri is not a repo: %s", r)),
65 )
66}
67
68var GitError = func(e error) XrpcError {
69 return NewXrpcError(
70 WithTag("Git"),
71 WithError(fmt.Errorf("git error: %w", e)),
72 )
73}
74
75var AccessControlError = func(d string) XrpcError {
76 return NewXrpcError(
77 WithTag("AccessControl"),
78 WithError(fmt.Errorf("DID does not have sufficent access permissions for this operation: %s", d)),
79 )
80}
81
82var RepoExistsError = func(r string) XrpcError {
83 return NewXrpcError(
84 WithTag("RepoExists"),
85 WithError(fmt.Errorf("repo already exists: %s", r)),
86 )
87}
88
89var RecordExistsError = func(r string) XrpcError {
90 return NewXrpcError(
91 WithTag("RecordExists"),
92 WithError(fmt.Errorf("repo already exists: %s", r)),
93 )
94}
95
96func GenericError(err error) XrpcError {
97 return NewXrpcError(
98 WithTag("Generic"),
99 WithError(err),
100 )
101}
102
103func Unmarshal(errStr string) (XrpcError, error) {
104 var xerr XrpcError
105 err := json.Unmarshal([]byte(errStr), &xerr)
106 if err != nil {
107 return XrpcError{}, fmt.Errorf("failed to unmarshal XrpcError: %w", err)
108 }
109 return xerr, nil
110}