Skip to content

Commit ff3e16d

Browse files
committed
add support for error handling
1 parent a247724 commit ff3e16d

File tree

3 files changed

+61
-2
lines changed

3 files changed

+61
-2
lines changed

python_http_client/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
from .client import Client
2+
from .exceptions import *

python_http_client/client.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
"""HTTP Client library"""
22
import json
3-
3+
from .exceptions import handle_error
44

55
try:
66
# Python 3
77
import urllib.request as urllib
88
from urllib.parse import urlencode
9+
from urllib.error import HTTPError
910
except ImportError:
1011
# Python 2
1112
import urllib2 as urllib
13+
from urllib2 import HTTPError
1214
from urllib import urlencode
1315

1416

@@ -135,7 +137,10 @@ def _make_request(self, opener, request):
135137
:type request: urllib.Request object
136138
:return: urllib response
137139
"""
138-
return opener.open(request)
140+
try:
141+
return opener.open(request)
142+
except HTTPError as err:
143+
handle_error(err)
139144

140145
def _(self, name):
141146
"""Add variable values to the url.

python_http_client/exceptions.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
class HTTPError(Exception):
2+
''' Base of all other errors'''
3+
def __init__(self,error):
4+
self.code = error.code
5+
self.reason = error.reason
6+
#self.headers = error.headers
7+
8+
class BadRequestsError(HTTPError):
9+
pass
10+
11+
class UnauthorizedError(HTTPError):
12+
pass
13+
14+
class ForbiddenError(HTTPError):
15+
pass
16+
17+
class NotFoundError(HTTPError):
18+
pass
19+
20+
class MethodNotAllowedError(HTTPError):
21+
pass
22+
23+
class PayloadTooLargeError(HTTPError):
24+
pass
25+
26+
class UnsupportedMediaTypeError(HTTPError):
27+
pass
28+
29+
class TooManyRequestsError(HTTPError):
30+
pass
31+
32+
class InternalServerError(HTTPError):
33+
pass
34+
35+
class ServiceUnavailableError(HTTPError):
36+
pass
37+
38+
err_dict = { 400 : BadRequestsError,
39+
401 : UnauthorizedError,
40+
403 : ForbiddenError,
41+
404 : NotFoundError,
42+
405 : MethodNotAllowedError,
43+
413 : PayloadTooLargeError,
44+
415 : UnsupportedMediaTypeError,
45+
429 : TooManyRequestsError,
46+
500 : InternalServerError,
47+
503 : ServiceUnavailableError
48+
}
49+
50+
def handle_error(error):
51+
exc = err_dict[error.code](error)
52+
exc.__cause__ = None
53+
raise exc

0 commit comments

Comments
 (0)