@@ -499,19 +499,22 @@ def _get_socket(
499499 )[0 ]
500500 retry_count = 0
501501 sock = None
502+ last_exc = None
502503 while retry_count < 5 and sock is None :
503504 if retry_count > 0 :
504505 if any (self ._socket_free .items ()):
505506 self ._free_sockets ()
506507 else :
507- raise RuntimeError ("Sending request failed" )
508+ raise RuntimeError ("Sending request failed" ) from last_exc
508509 retry_count += 1
509510
510511 try :
511512 sock = self ._socket_pool .socket (addr_info [0 ], addr_info [1 ])
512- except OSError :
513+ except OSError as exc :
514+ last_exc = exc
513515 continue
514- except RuntimeError :
516+ except RuntimeError as exc :
517+ last_exc = exc
515518 continue
516519
517520 connect_host = addr_info [- 1 ][0 ]
@@ -522,15 +525,17 @@ def _get_socket(
522525
523526 try :
524527 sock .connect ((connect_host , port ))
525- except MemoryError :
528+ except MemoryError as exc :
529+ last_exc = exc
526530 sock .close ()
527531 sock = None
528- except OSError :
532+ except OSError as exc :
533+ last_exc = exc
529534 sock .close ()
530535 sock = None
531536
532537 if sock is None :
533- raise RuntimeError ("Repeated socket failures" )
538+ raise RuntimeError ("Repeated socket failures" ) from last_exc
534539
535540 self ._open_sockets [key ] = sock
536541 self ._socket_free [sock ] = False
@@ -650,13 +655,15 @@ def request(
650655 # We may fail to send the request if the socket we got is closed already. So, try a second
651656 # time in that case.
652657 retry_count = 0
658+ last_exc = None
653659 while retry_count < 2 :
654660 retry_count += 1
655661 socket = self ._get_socket (host , port , proto , timeout = timeout )
656662 ok = True
657663 try :
658664 self ._send_request (socket , host , method , path , headers , data , json )
659- except OSError :
665+ except OSError as exc :
666+ last_exc = exc
660667 ok = False
661668 if ok :
662669 # Read the H of "HTTP/1.1" to make sure the socket is alive. send can appear to work
@@ -676,7 +683,7 @@ def request(
676683 socket = None
677684
678685 if not socket :
679- raise OutOfRetries ("Repeated socket failures" )
686+ raise OutOfRetries ("Repeated socket failures" ) from last_exc
680687
681688 resp = Response (socket , self ) # our response
682689 if "location" in resp .headers and 300 <= resp .status_code <= 399 :
0 commit comments