0

I am a newbie in python software development. I have created a script which includes many functions returning output of a request and handling the exceptions generated by them. One of the func. is as below:

def ApiResponse(emailHash):
    r=None
    errorMessage = ""
    url = "https://dummy.com" 
    try:
        r = requests.get(url, timeout = TIMEOUT_LIMIT)
    except requests.exceptions.Timeout as e:
        errorMessage = "Timeout Error"
    except requests.ConnectionError as e:
        errorMessage = "ConnectionError"
    except requests.RequestException as e:
        errorMessage = "Some other Request Exception"
    return r 

I have many such functions returning response for different requests. But, they all repeat the exception handling code. I want to handle exceptions separately in another function so that I don't have to repeat myself. I have tried stuff like passing on the variable "e" to other function and comparing it to the exception types and return different error messages accordingly but I cant seem to compare, lets say, e == requests.exceptions.Timeout.

What else can i do just to separate out that exception handling part? I aim to write a modular code!

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

1

You can use exception-decouple package for good readbility:

from exception_decouple import redirect_exceptions


def timeout_handler(emailHash, e):
    return "Timeout Error"


def default_handler(emailHash, e):
    return "Other Error"


@redirect_exceptions(timeout_handler, requests.exceptions.Timeout)
@redirect_exceptions(default_handler, requests.ConnectionError,
                                      requests.RequestException)
def ApiResponse(emailHash):
    r=None
    url = "https://dummy.com" 
    r = requests.get(url, timeout = TIMEOUT_LIMIT)
    return r 
0

one of the ways I found was to compare the type of the error with the error. for example in the above case.

def exception_handler(e):
    if type(e) is requests.exceptions.ConnectTimeout:
        return "Timeout Error"
    elif type(e) is requests.ConnectionError:
        return "ConnectionError"
    else:
        return "Some other Request Exception"

this should work