Skip to content

Commit ef540cd

Browse files
committed
Handle JSON parsing errors
1 parent 4727587 commit ef540cd

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

detectlanguage/api.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,3 @@ def user_status():
1313

1414
def languages():
1515
return detectlanguage.client.get('languages')
16-

detectlanguage/client.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import requests
22

33
from .exceptions import *
4+
from requests.exceptions import HTTPError
5+
6+
try:
7+
from json.decoder import JSONDecodeError
8+
except ImportError:
9+
JSONDecodeError = ValueError
410

511
class Client:
612
def __init__(self, configuration):
@@ -15,14 +21,25 @@ def post(self, path, payload):
1521
return self.handle_response(r)
1622

1723
def handle_response(self, r):
18-
json = r.json()
24+
try:
25+
r.raise_for_status()
1926

20-
if 'error' in json:
21-
raise DetectLanguageError(json['error']['message'])
27+
return r.json()
28+
except HTTPError as err:
29+
self.handle_http_error(r, err)
30+
except JSONDecodeError:
31+
raise DetectLanguageError("Error decoding response JSON")
2232

23-
r.raise_for_status()
33+
def handle_http_error(self, r, err):
34+
try:
35+
json = r.json()
2436

25-
return json
37+
if not 'error' in json:
38+
raise DetectLanguageError(err)
39+
40+
raise DetectLanguageError(json['error']['message'])
41+
except JSONDecodeError:
42+
raise DetectLanguageError(err)
2643

2744
def url(self, path):
2845
return "%s://%s/%s/%s" % (self.protocol(), self.configuration.host, self.configuration.api_version, path)

0 commit comments

Comments
 (0)