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.

4
  • 1
    wrap you requests in a try/except block? without seeing your code its hard to give you any sort of advice Commented Jan 26, 2020 at 11:37
  • @Nullman I have updated the question, hope you will understand Commented Jan 26, 2020 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 Commented Jan 26, 2020 at 11:51
  • Does this answer your question? how to not have the flask server break when an error occurs? Commented Jan 28, 2020 at 8:53

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.