forked from tangled.org/core
Monorepo for Tangled — https://tangled.org
at master 2.5 kB view raw
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 AuthError = func(err error) XrpcError { 70 return NewXrpcError( 71 WithTag("Auth"), 72 WithError(fmt.Errorf("signature verification failed: %w", err)), 73 ) 74} 75 76var InvalidRepoError = func(r string) XrpcError { 77 return NewXrpcError( 78 WithTag("InvalidRepo"), 79 WithError(fmt.Errorf("supplied at-uri is not a repo: %s", r)), 80 ) 81} 82 83var GitError = func(e error) XrpcError { 84 return NewXrpcError( 85 WithTag("Git"), 86 WithError(fmt.Errorf("git error: %w", e)), 87 ) 88} 89 90var AccessControlError = func(d string) XrpcError { 91 return NewXrpcError( 92 WithTag("AccessControl"), 93 WithError(fmt.Errorf("DID does not have sufficent access permissions for this operation: %s", d)), 94 ) 95} 96 97var RepoExistsError = func(r string) XrpcError { 98 return NewXrpcError( 99 WithTag("RepoExists"), 100 WithError(fmt.Errorf("repo already exists: %s", r)), 101 ) 102} 103 104var RecordExistsError = func(r string) XrpcError { 105 return NewXrpcError( 106 WithTag("RecordExists"), 107 WithError(fmt.Errorf("repo already exists: %s", r)), 108 ) 109} 110 111func GenericError(err error) XrpcError { 112 return NewXrpcError( 113 WithTag("Generic"), 114 WithError(err), 115 ) 116} 117 118func Unmarshal(errStr string) (XrpcError, error) { 119 var xerr XrpcError 120 err := json.Unmarshal([]byte(errStr), &xerr) 121 if err != nil { 122 return XrpcError{}, fmt.Errorf("failed to unmarshal XrpcError: %w", err) 123 } 124 return xerr, nil 125}