Skip to content

Commit a5d4928

Browse files
committed
translate: catch requests exceptions
1 parent 677cdbf commit a5d4928

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

sopel/modules/translate.py

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from __future__ import generator_stop
1010

1111
import json
12+
import logging
1213
import random
1314

1415
import requests
@@ -17,6 +18,7 @@
1718
from sopel.tools import web
1819

1920

21+
LOGGER = logging.getLogger(__name__)
2022
PLUGIN_OUTPUT_PREFIX = '[translate] '
2123

2224

@@ -64,6 +66,9 @@ def translate(text, in_lang='auto', out_lang='en'):
6466
try:
6567
data = json.loads(result)
6668
except ValueError:
69+
LOGGER.error(
70+
'Error parsing JSON response from translate API (%s to %s: "%s")',
71+
in_lang, out_lang, text)
6772
return None, None
6873

6974
if raw:
@@ -100,7 +105,21 @@ def tr(bot, trigger):
100105
bot.reply('Language guessing failed, so try suggesting one!')
101106
return
102107

103-
msg, in_lang = translate(phrase, in_lang, out_lang)
108+
try:
109+
msg, in_lang = translate(phrase, in_lang, out_lang)
110+
except requests.Timeout:
111+
bot.reply("Translation service unavailable (timeout).")
112+
LOGGER.error(
113+
'Translate API error (%s to %s: "%s"): timeout.',
114+
in_lang, out_lang, phrase)
115+
return
116+
except requests.RequestException as http_error:
117+
bot.reply("Translation request failed.")
118+
LOGGER.exception(
119+
'Translate API error (%s to %s: "%s"): %s.',
120+
in_lang, out_lang, phrase, http_error)
121+
return
122+
104123
if not in_lang:
105124
bot.reply("Translation failed, probably because of a rate-limit.")
106125
return
@@ -164,7 +183,21 @@ def langcode(p):
164183
bot.reply('Language guessing failed, so try suggesting one!')
165184
return
166185

167-
msg, src = translate(phrase, src, dest)
186+
try:
187+
msg, src = translate(phrase, src, dest)
188+
except requests.Timeout:
189+
bot.reply("Translation service unavailable (timeout).")
190+
LOGGER.error(
191+
'Translate API error (%s to %s: "%s"): timeout.',
192+
src, dest, phrase)
193+
return
194+
except requests.RequestException as http_error:
195+
bot.reply("Translation request failed.")
196+
LOGGER.exception(
197+
'Translate API error (%s to %s: "%s"): %s.',
198+
src, dest, phrase, http_error)
199+
return
200+
168201
if not src:
169202
return bot.say("Translation failed, probably because of a rate-limit.")
170203

0 commit comments

Comments
 (0)