Debian Codegraph @

plugin/errors.go

raw symbols SCIP
1 // Copyright The Notary Project Authors.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package plugin
15
16 import (
17 "encoding/json"
18 "fmt"
19 )
20
21 type ErrorCode string
22
23 const (
24 ErrorCodeValidation ErrorCode = "VALIDATION_ERROR"
25 ErrorCodeUnsupportedContractVersion ErrorCode = "UNSUPPORTED_CONTRACT_VERSION"
26 ErrorCodeAccessDenied ErrorCode = "ACCESS_DENIED"
27 ErrorCodeTimeout ErrorCode = "TIMEOUT"
28 ErrorCodeThrottled ErrorCode = "THROTTLED"
29 ErrorCodeGeneric ErrorCode = "ERROR"
30 )
31
32 const (
33 ErrorMsgMalformedInput string = "Input is not a valid JSON"
34 ErrorMsgMalformedOutputFmt string = "Failed to generate response. Error: %s"
35 )
36
37 // Error is used to return a well-formed error response as per NotaryProject specification.
38 type Error struct {
39 ErrCode ErrorCode `json:"errorCode"`
40 Message string `json:"errorMessage,omitempty"`
41 Metadata map[string]string `json:"errorMetadata,omitempty"`
42 }
43
44 func NewError(code ErrorCode, msg string) *Error {
45 return &Error{
46 ErrCode: code,
47 Message: msg,
48 }
49 }
50
51 func NewGenericError(msg string) *Error {
52 return NewError(ErrorCodeGeneric, msg)
53 }
54
55 func NewGenericErrorf(format string, msg ...any) *Error {
56 return NewError(ErrorCodeGeneric, fmt.Sprintf(format, msg...))
57 }
58
59 func NewUnsupportedError(msg string) *Error {
60 return NewError(ErrorCodeValidation, msg+" is not supported")
61 }
62
63 func NewValidationError(msg string) *Error {
64 return NewError(ErrorCodeValidation, msg)
65 }
66
67 func NewValidationErrorf(format string, msg ...any) *Error {
68 return NewError(ErrorCodeValidation, fmt.Sprintf(format, msg...))
69 }
70
71 func NewUnsupportedContractVersionError(version string) *Error {
72 return NewError(ErrorCodeUnsupportedContractVersion, fmt.Sprintf("%q is not a supported notary plugin contract version", version))
73 }
74
75 func NewJSONParsingError(msg string) *Error {
76 return NewValidationError(msg)
77 }
78
79 // Error returns the formatted error message.
80 func (e *Error) Error() string {
81 op, err := json.Marshal(e)
82 if err != nil {
83 return "something went wrong"
84 }
85 return string(op)
86 }