fix(error-handling): improve article fetch error handling

Added try-except block to handle HTTP errors when fetching wiki articles. Specifically, handle 404 errors with a user-friendly "Article not found" message and log other errors with a generic error message displayed to the user. This enhances user experience by providing clearer feedback and more robust error logging.
This commit is contained in:
Kumi 2024-08-19 17:01:59 +02:00
parent ac5e542727
commit a4272eaf8e
Signed by: kumi
GPG key ID: ECBCC9082395383F

View file

@ -148,8 +148,29 @@ def wiki_article(project, lang, title):
if request.args.get("variant", None):
api_request.add_header("Accept-Language", f"{request.args['variant']}")
with urllib.request.urlopen(api_request) as response:
article_html = response.read().decode()
try:
with urllib.request.urlopen(api_request) as response:
article_html = response.read().decode()
except urllib.error.HTTPError as e:
if e.code == 404:
return (
render_template(
"article.html",
title="Article not found",
content=f"Sorry, the article {title} was not found in the {project} project in the {lang} language.",
),
404,
)
else:
logger.error(f"Error fetching article {title} from {lang}.{project}: {e}")
return (
render_template(
"article.html",
title="Error",
content=f"An error occurred while fetching the article {title} from the {project} project in the {lang} language.",
),
500,
)
soup = BeautifulSoup(article_html, "html.parser")