Skip to content

Commit ca10057

Browse files
authored
Merge pull request #133 from deploymenttheory/dev
Refactor parseHTMLResponse to concatenate all text within <p> tags
2 parents 0533ae5 + b40f4ea commit ca10057

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

Diff for: response/error.go

+14-8
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ func parseTextResponse(bodyBytes []byte, apiError *APIError, log logger.Logger,
154154
logError(log, apiError, "text_error_detected", resp)
155155
}
156156

157-
// parseHTMLResponse extracts meaningful information from an HTML error response.
157+
// parseHTMLResponse extracts meaningful information from an HTML error response and concatenates all text within <p> tags.
158158
func parseHTMLResponse(bodyBytes []byte, apiError *APIError, log logger.Logger, resp *http.Response) {
159159
// Always set the Raw field to the entire HTML content for debugging purposes
160160
apiError.Raw = string(bodyBytes)
@@ -166,26 +166,32 @@ func parseHTMLResponse(bodyBytes []byte, apiError *APIError, log logger.Logger,
166166
return
167167
}
168168

169+
var messages []string // To accumulate messages from all <p> tags
169170
var parse func(*html.Node)
170171
parse = func(n *html.Node) {
171172
if n.Type == html.ElementNode && n.Data == "p" {
172-
if n.FirstChild != nil {
173-
apiError.Message = n.FirstChild.Data
174-
// Optionally, you might break or return after finding the first relevant message
173+
for c := n.FirstChild; c != nil; c = c.NextSibling {
174+
if c.Type == html.TextNode {
175+
// Accumulate text content of <p> tag
176+
messages = append(messages, c.Data)
177+
}
175178
}
176179
}
177180
for c := n.FirstChild; c != nil; c = c.NextSibling {
178-
parse(c)
181+
parse(c) // Recursively parse the document
179182
}
180183
}
181184

182185
parse(doc)
183186

184-
// If no <p> tag was found or it was empty, fallback to using the raw HTML
185-
if apiError.Message == "" {
187+
// Concatenate all accumulated messages with a separator
188+
if len(messages) > 0 {
189+
apiError.Message = strings.Join(messages, "; ")
190+
} else {
191+
// Fallback error message if no specific messages were extracted
186192
apiError.Message = "HTML Error: See 'Raw' field for details."
187-
apiError.Raw = string(bodyBytes)
188193
}
194+
189195
// Log the extracted error message or the fallback message
190196
logError(log, apiError, "html_error_detected", resp)
191197
}

0 commit comments

Comments
 (0)