Skip to content

Commit 075647b

Browse files
committed
add StanfordCoreNLPError, do not hide json parsing errors
1 parent 8fb3d44 commit 075647b

File tree

1 file changed

+17
-17
lines changed

1 file changed

+17
-17
lines changed

pycorenlp/corenlp.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,15 @@ def __str__(self):
1010
'$ java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer'
1111
% (self.server_url))
1212

13-
class StanfordCoreNLP:
13+
class StanfordCoreNLPError(Exception):
14+
def __init__(self, reason, message):
15+
self.reason = reason
16+
self.message = message
17+
18+
def __str__(self):
19+
return "%s(%s): %s" % (self.__class__.__name__,self.reason,self.message)
1420

21+
class StanfordCoreNLP:
1522
def __init__(self, server_url):
1623
if server_url[-1] == '/':
1724
server_url = server_url[:-1]
@@ -30,19 +37,15 @@ def annotate(self, text, properties=None):
3037
except requests.exceptions.ConnectionError:
3138
raise NoStanfordCoreNLPServer(self.server_url)
3239

33-
data = text.encode()
3440
r = requests.post(
3541
self.server_url, params={
3642
'properties': str(properties)
37-
}, data=data, headers={'Connection': 'close'})
38-
output = r.text
39-
if ('outputFormat' in properties
40-
and properties['outputFormat'] == 'json'):
41-
try:
42-
output = json.loads(output, strict=True)
43-
except:
44-
pass
45-
return output
43+
}, data=text.encode(), headers={'Connection': 'close'})
44+
if not r.ok:
45+
raise StanfordCoreNLPError(r.reason, r.text)
46+
if properties.get('outputFormat') == 'json':
47+
return json.loads(r.text)
48+
return r.text
4649

4750
def tokensregex(self, text, pattern, filter):
4851
return self.regex('/tokensregex', text, pattern, filter)
@@ -56,9 +59,6 @@ def regex(self, endpoint, text, pattern, filter):
5659
'pattern': pattern,
5760
'filter': filter
5861
}, data=text)
59-
output = r.text
60-
try:
61-
output = json.loads(r.text)
62-
except:
63-
pass
64-
return output
62+
if not r.ok:
63+
raise StanfordCoreNLPError(r.reason, r.text)
64+
return json.loads(r.text)

0 commit comments

Comments
 (0)