@@ -499,19 +499,22 @@ def _get_socket(
499
499
)[0 ]
500
500
retry_count = 0
501
501
sock = None
502
+ last_exc = None
502
503
while retry_count < 5 and sock is None :
503
504
if retry_count > 0 :
504
505
if any (self ._socket_free .items ()):
505
506
self ._free_sockets ()
506
507
else :
507
- raise RuntimeError ("Sending request failed" )
508
+ raise RuntimeError ("Sending request failed" ) from last_exc
508
509
retry_count += 1
509
510
510
511
try :
511
512
sock = self ._socket_pool .socket (addr_info [0 ], addr_info [1 ])
512
- except OSError :
513
+ except OSError as exc :
514
+ last_exc = exc
513
515
continue
514
- except RuntimeError :
516
+ except RuntimeError as exc :
517
+ last_exc = exc
515
518
continue
516
519
517
520
connect_host = addr_info [- 1 ][0 ]
@@ -522,15 +525,17 @@ def _get_socket(
522
525
523
526
try :
524
527
sock .connect ((connect_host , port ))
525
- except MemoryError :
528
+ except MemoryError as exc :
529
+ last_exc = exc
526
530
sock .close ()
527
531
sock = None
528
- except OSError :
532
+ except OSError as exc :
533
+ last_exc = exc
529
534
sock .close ()
530
535
sock = None
531
536
532
537
if sock is None :
533
- raise RuntimeError ("Repeated socket failures" )
538
+ raise RuntimeError ("Repeated socket failures" ) from last_exc
534
539
535
540
self ._open_sockets [key ] = sock
536
541
self ._socket_free [sock ] = False
@@ -650,13 +655,15 @@ def request(
650
655
# We may fail to send the request if the socket we got is closed already. So, try a second
651
656
# time in that case.
652
657
retry_count = 0
658
+ last_exc = None
653
659
while retry_count < 2 :
654
660
retry_count += 1
655
661
socket = self ._get_socket (host , port , proto , timeout = timeout )
656
662
ok = True
657
663
try :
658
664
self ._send_request (socket , host , method , path , headers , data , json )
659
- except OSError :
665
+ except OSError as exc :
666
+ last_exc = exc
660
667
ok = False
661
668
if ok :
662
669
# 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(
676
683
socket = None
677
684
678
685
if not socket :
679
- raise OutOfRetries ("Repeated socket failures" )
686
+ raise OutOfRetries ("Repeated socket failures" ) from last_exc
680
687
681
688
resp = Response (socket , self ) # our response
682
689
if "location" in resp .headers and 300 <= resp .status_code <= 399 :
0 commit comments