Skip to content

Commit 8866ba2

Browse files
authored
Fix ValueError from invalid CSS selectors in EmbedAPI (#12573)
This PR adds defensive handling for invalid CSS selectors in the EmbedAPI to prevent crashes. ## Changes - Added try-except blocks around calls to catch exceptions - Invalid selectors now log a warning and return None instead of crashing - Applies to both the query parameter and fragment-based selectors ## Issue Fixes: https://read-the-docs.sentry.io/issues/6923723755/ Previously, when malformed CSS selectors like `@@R06GA` were passed, selectolax would raise a ValueError that wasn't caught, causing the entire request to fail.
1 parent f3708e1 commit 8866ba2

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

readthedocs/embed/v3/views.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,11 @@ def _get_content_by_fragment(
147147

148148
def _find_main_node(self, html, selector):
149149
if selector:
150-
return html.css_first(selector)
150+
try:
151+
return html.css_first(selector)
152+
except ValueError:
153+
log.warning("Invalid CSS selector provided.", selector=selector)
154+
return None
151155

152156
main_node = html.css_first("[role=main]")
153157
if main_node:
@@ -183,7 +187,11 @@ def _parse_based_on_doctool(
183187
# characters as the `id=` HTML attribute
184188
# https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
185189
selector = f'[id="{fragment}"]'
186-
node = HTMLParser(page_content).css_first(selector)
190+
try:
191+
node = HTMLParser(page_content).css_first(selector)
192+
except ValueError:
193+
log.warning("Invalid CSS selector from fragment.", fragment=fragment)
194+
node = None
187195
else:
188196
html = HTMLParser(page_content)
189197
node = self._find_main_node(html, selector)

0 commit comments

Comments
 (0)