@@ -2,6 +2,7 @@ package upcloud
22
33import (
44 "fmt"
5+ "net/url"
56 "strings"
67)
78
@@ -14,12 +15,19 @@ type Problem struct {
1415 // InvalidParams if set, is a list of ProblemInvalidParam describing a specific part(s) of the request
1516 // that caused the problem
1617 InvalidParams []ProblemInvalidParam `json:"invalid_params,omitempty"`
17- // CorrelationID is an unique string that identifies the request that caused the problem
18+ // CorrelationID is a unique string that identifies the request that caused the problem
19+ // Please note that it is not always available
1820 CorrelationID string `json:"correlation_id,omitempty"`
1921 // HTTP Status code
2022 Status int `json:"status"`
2123}
2224
25+ // ProblemInvalidParam is a type describing extra information in the Problem type's InvalidParams field.
26+ type ProblemInvalidParam struct {
27+ Name string `json:"name"`
28+ Reason string `json:"reason"`
29+ }
30+
2331func (p * Problem ) Error () string {
2432 var sb strings.Builder
2533 _ , _ = fmt .Fprintf (& sb , "error: message=%q, type=%q" , p .Title , p .Type )
@@ -34,8 +42,15 @@ func (p *Problem) Error() string {
3442 return sb .String ()
3543}
3644
37- // ProblemInvalidParam is a type describing extra information in the Problem type's InvalidParams field.
38- type ProblemInvalidParam struct {
39- Name string `json:"name"`
40- Reason string `json:"reason"`
45+ // ErrorCode returns a short string that identifies the error; it should be used for programmatic comparisons
46+ func (p * Problem ) ErrorCode () string {
47+ // First check if the type is a URL.
48+ // If it is - we need to extract meaningful fragment from it for comparison purposes
49+ // If it isn't - we can just return the value of `Type` field
50+ parsedURL , err := url .Parse (p .Type )
51+ if err != nil || parsedURL .Scheme == "" || parsedURL .Host == "" {
52+ return p .Type
53+ }
54+
55+ return strings .Replace (parsedURL .Fragment , "ERROR_" , "" , 1 )
4156}
0 commit comments