0

Within my code, all requests have a timeout period. And for each request, I have to handle the Timeout exception. Is there any way to attach a global Timeout exception handler with the requests?

try:
  request = requests.post(url=url1, data=data, headers=headers, timeout=Config.REQUEST_TIMEOUT)
except Timeout:
  raise ServiceUnavailable()

try:
  request = requests.post(url=url2, data=data, headers=headers, timeout=Config.REQUEST_TIMEOUT)
except Timeout:
  raise ServiceUnavailable()

Like above I every time I have to handle timeout and raise service unavailable. I want something generic, whenever timeout occurs it will raise service unavailable.

Minuddin Ahmed Rana
  • 1,084
  • 1
  • 15
  • 27
  • 1
    wrap you requests in a try/except block? without seeing your code its hard to give you any sort of advice – Nullman Jan 26 '20 at 11:37
  • @Nullman I have updated the question, hope you will understand – Minuddin Ahmed Rana Jan 26 '20 at 11:46
  • 1
    you could subclass requests and decorate the `post` method to handle the exception internally, that way you wont have to keep writing the same exception handler over and over – Nullman Jan 26 '20 at 11:51
  • Does this answer your question? [how to not have the flask server break when an error occurs?](https://stackoverflow.com/questions/59786044/how-to-not-have-the-flask-server-break-when-an-error-occurs) – Gaurav Agarwal Jan 28 '20 at 08:53

1 Answers1

1

Solved the problem using a different way. I am using flask, so I have added an error handler for Timeout exception

@app.errorhandler(requests.exceptions.Timeout)
def third_party_communication_handler(e):
    raise ServiceUnavailable()
Minuddin Ahmed Rana
  • 1,084
  • 1
  • 15
  • 27