diff --git a/python_http_client/__init__.py b/python_http_client/__init__.py index 3ff722b..d616f8c 100644 --- a/python_http_client/__init__.py +++ b/python_http_client/__init__.py @@ -1 +1,2 @@ from .client import Client +from .exceptions import * \ No newline at end of file diff --git a/python_http_client/client.py b/python_http_client/client.py index dd24c48..2ace81e 100644 --- a/python_http_client/client.py +++ b/python_http_client/client.py @@ -1,14 +1,16 @@ """HTTP Client library""" import json - +from .exceptions import handle_error try: # Python 3 import urllib.request as urllib from urllib.parse import urlencode + from urllib.error import HTTPError except ImportError: # Python 2 import urllib2 as urllib + from urllib2 import HTTPError from urllib import urlencode @@ -135,7 +137,10 @@ def _make_request(self, opener, request): :type request: urllib.Request object :return: urllib response """ - return opener.open(request) + try: + return opener.open(request) + except HTTPError as err: + handle_error(err) def _(self, name): """Add variable values to the url. diff --git a/python_http_client/exceptions.py b/python_http_client/exceptions.py new file mode 100644 index 0000000..7d447d8 --- /dev/null +++ b/python_http_client/exceptions.py @@ -0,0 +1,53 @@ +class HTTPError(Exception): + ''' Base of all other errors''' + def __init__(self,error): + self.code = error.code + self.reason = error.reason + #self.headers = error.headers + +class BadRequestsError(HTTPError): + pass + +class UnauthorizedError(HTTPError): + pass + +class ForbiddenError(HTTPError): + pass + +class NotFoundError(HTTPError): + pass + +class MethodNotAllowedError(HTTPError): + pass + +class PayloadTooLargeError(HTTPError): + pass + +class UnsupportedMediaTypeError(HTTPError): + pass + +class TooManyRequestsError(HTTPError): + pass + +class InternalServerError(HTTPError): + pass + +class ServiceUnavailableError(HTTPError): + pass + +err_dict = { 400 : BadRequestsError, + 401 : UnauthorizedError, + 403 : ForbiddenError, + 404 : NotFoundError, + 405 : MethodNotAllowedError, + 413 : PayloadTooLargeError, + 415 : UnsupportedMediaTypeError, + 429 : TooManyRequestsError, + 500 : InternalServerError, + 503 : ServiceUnavailableError +} + +def handle_error(error): + exc = err_dict[error.code](error) + exc.__cause__ = None + raise exc