Python调用API时SSL异常捕获失败问题求助
Let’s address why your requests.exceptions.SSLError isn’t being caught, along with actionable fixes:
1. Confirm Try-Except Wraps the Entire Request Flow
Ensure every line of code that triggers the API call is enclosed in the try block. If your something() function calls nested functions to make the request, check that none of those nested functions have their own try-except blocks that swallow or re-raise the exception without propagating it upward.
2. Catch Both Requests and Raw SSL Exceptions
In edge cases, the underlying ssl.SSLError might bubble up instead of being fully wrapped by requests. Add a second except clause to cover both:
import ssl import requests import sys def make_api_call(): # Replace with your actual API request logic response = requests.post( "https://192.168.0.1/api/sonicos/auth", json={"username": "your_user", "password": "your_pass"} ) response.raise_for_status() # Ensure HTTP errors trigger exceptions return response try: make_api_call() except requests.exceptions.SSLError as req_ssl_err: print(f"Connection limit or SSL issue: {req_ssl_err}") sys.exit(0) except ssl.SSLError as raw_ssl_err: print(f"Raw SSL error: {raw_ssl_err}") sys.exit(0)
3. Use a Broader Exception Catch for Debugging
If the above doesn’t work, temporarily catch all requests.exceptions.RequestException (the parent class for all requests-related errors) to confirm the exception type being raised:
try: make_api_call() except requests.exceptions.RequestException as e: print(f"Request failed: {type(e).__name__} - {e}") sys.exit(0)
This will print the exact exception class, helping you target it correctly in your final code.
4. Check for Unhandled Exceptions in Nested Code
Verify no code inside something() is catching exceptions silently. For example, a nested try-except that catches Exception but doesn’t re-raise it will prevent your outer try-except from seeing the error.
Additional Context
The DH_KEY_TOO_SMALL error often stems from the firewall using a weak Diffie-Hellman cipher suite. While concurrent connections trigger it in your scenario, updating the firewall’s SSL configuration (using stronger DH keys or modern ciphers) would eliminate the error entirely. The fixes above ensure your script catches the error and exits cleanly as intended.
内容的提问来源于stack exchange,提问作者pandapunk94

