Skip to content

Instantly share code, notes, and snippets.

@Praveen005
Created July 22, 2024 14:12
Show Gist options
  • Save Praveen005/b52bd67e6b68c2339328e65dc3b28ba1 to your computer and use it in GitHub Desktop.
Save Praveen005/b52bd67e6b68c2339328e65dc3b28ba1 to your computer and use it in GitHub Desktop.
extracting json part from the error message.
// CustomError stores a part of the complete API error
type CustomError struct {
Code string `json:"code"`
Reason string `json:"reason"`
}
// Error implements the error interface
func (e *CustomError) Error() string {
return fmt.Sprintf("%s - %s", e.Code, e.Reason)
}
var jsonRegex *regexp.Regexp
var once sync.Once
var regexErr error
func getJSONRegex() (*regexp.Regexp, error) {
once.Do(func() {
jsonRegex, regexErr = regexp.Compile(`\{.*\}`)
})
return jsonRegex, regexErr
}
// extractJSON uses regex to find JSON content within a string
func extractJSON(s string) (string, error) {
re, err := getJSONRegex()
if err != nil {
return "", fmt.Errorf("failed to compile regex: %v", err)
}
match := re.FindString(s)
if match == "" {
return "", fmt.Errorf("no JSON object found in the string")
}
return match, nil
}
// ParseErrorResponse extracts and parses the JSON error response
func ParseErrorResponse(errorMsg string) (*CustomError, error) {
jsonStr, err := extractJSON(errorMsg)
if err != nil {
return nil, fmt.Errorf("failed to extract JSON: %v", err)
}
var customErr CustomError
err = json.Unmarshal([]byte(jsonStr), &customErr)
if err != nil {
return nil, fmt.Errorf("failed to parse error response: %v", err)
}
return &customErr, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment