forked from
tangled.org/core
Monorepo for Tangled
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 OwnerNotFoundError = NewXrpcError(
55 WithTag("OwnerNotFound"),
56 WithMessage("owner not set for this service"),
57)
58
59var RepoNotFoundError = NewXrpcError(
60 WithTag("RepoNotFound"),
61 WithMessage("failed to access repository"),
62)
63
64var RefNotFoundError = NewXrpcError(
65 WithTag("RefNotFound"),
66 WithMessage("failed to access ref"),
67)
68
69var RequestTooLargeError = NewXrpcError(
70 WithTag("RequestTooLarge"),
71 WithMessage("request was too large"),
72)
73
74var AuthError = func(err error) XrpcError {
75 return NewXrpcError(
76 WithTag("Auth"),
77 WithError(fmt.Errorf("signature verification failed: %w", err)),
78 )
79}
80
81var InvalidRepoError = func(r string) XrpcError {
82 return NewXrpcError(
83 WithTag("InvalidRepo"),
84 WithError(fmt.Errorf("supplied at-uri is not a repo: %s", r)),
85 )
86}
87
88var GitError = func(e error) XrpcError {
89 return NewXrpcError(
90 WithTag("Git"),
91 WithError(fmt.Errorf("git error: %w", e)),
92 )
93}
94
95var AccessControlError = func(d string) XrpcError {
96 return NewXrpcError(
97 WithTag("AccessControl"),
98 WithError(fmt.Errorf("DID does not have sufficient access permissions for this operation: %s", d)),
99 )
100}
101
102var RepoExistsError = func(r string) XrpcError {
103 return NewXrpcError(
104 WithTag("RepoExists"),
105 WithError(fmt.Errorf("repo already exists: %s", r)),
106 )
107}
108
109var RecordExistsError = func(r string) XrpcError {
110 return NewXrpcError(
111 WithTag("RecordExists"),
112 WithError(fmt.Errorf("repo already exists: %s", r)),
113 )
114}
115
116func GenericError(err error) XrpcError {
117 return NewXrpcError(
118 WithTag("Generic"),
119 WithError(err),
120 )
121}
122
123func Unmarshal(errStr string) (XrpcError, error) {
124 var xerr XrpcError
125 err := json.Unmarshal([]byte(errStr), &xerr)
126 if err != nil {
127 return XrpcError{}, fmt.Errorf("failed to unmarshal XrpcError: %w", err)
128 }
129 return xerr, nil
130}