Exception handling during Python API communication

When creating an automatic trading BOT for virtual currency When using the API of the exchange, errors are frequently detected on the exchange side. Exception handling was implemented as a countermeasure. I will leave it as a memo for myself so that I will not forget it.

What is exception handling?

It is a simple countermeasure such as server error. Even if the code you write is correct, you may get an error at runtime. For example, when you make a request to an external server, the server is busy or For example, if the server is temporarily under maintenance and the server is not running. A server error (error code) etc. will be returned as a response result. Especially for programs that run automatically, such as automatic trading BOT It would be a problem if it was stopped every time due to a server error. .. .. (No longer an automatic trading BOT)

As a countermeasure, you can prevent unexpected errors by writing a try-except statement (exception handling).

HTTP status code

You can check whether the correct response to the squirrel quest was obtained by the HTTP status code. The following is a part of the HTTP status code, and the major classification is like this. I often got errors in the 500s.

--100s: Processing --200s: Success --300s: Redirect --400s: Client error --500s: Server error

sample.py


response = requests.get("https://***********")
print(response.status_code)

You can check the HTTP status code with Response object .status_code like the above code.

try-except statement

sample.py


try:
    response = requests.get("https://***********")
    response.raise_for_status() # 
    print(response.status_code)
except requests.exceptions.RequestException as e:
    print("error: ",e)

An exception may occur in the try: part, but the process you want to execute ʻExcept: Describe the processing when an exception occurs in the` part.

In the case of the above code, request communication is made to the external server by GET method and the response result is Check the HTTP status code with the raise_for_status () method, and if it is in the 200s, only the try: part will be executed. On the contrary, if the HTTP status code is other than the 200s, it is considered that an exception has occurred. ʻExcept:` part is executed.

The raise_for_status () method checks if the HTTP status code is in the 200s and If it is not in the 200s, it raises an exception, that is, it spits out an error and stops.

except is written as ʻexcept exception type as variable name: Exception objects (such as error messages) can be stored and used in variables. The variable name can be any name, but it is common to write ʻe or ʻerr`. You can check the content of the error by outputting the variable. For exception types, search for "library name exception handling", "library name error handling", etc. Most of the time you may want to know.

else clause

sample.py


try:
    response = requests.get("https://***********")
    response.raise_for_status()
except requests.exceptions.RequestException as e:
    print("error: ",e)
else:
    print("Processed successfully")

In the ʻelse: part, describe the processing to be performed after normal completion without exception. If an exception occurs and the ʻexcept: part is executed, the ʻelse:` part is not executed.

finally clause

sample.py


try:
    response = requests.get("https://***********")
    response.raise_for_status()
except requests.exceptions.RequestException as e:
    print("error: ",e)
else:
    print("Processed successfully")
finally:
    print("Always process on exit")

In the finally: part, describe the process you want to do last regardless of the occurrence of an exception. You can also use ʻelse:andfinally:at the same time. At the time of normal termination, the process offinally: is executed after the process of ʻelse: is executed.

Recommended Posts

Exception handling during Python API communication
Python exception handling
Python exception handling
Python, about exception handling
pip install mysql-Error handling during python
Exception handling
I tried to summarize Python exception handling
[Introduction to Udemy Python3 + Application] 65. Exception handling
Pharmaceutical company researchers summarized Python exception handling
Python exception handling a little more convenient
Module import and exception handling in python
Python Error Handling
boto3 exception handling
Python timezone handling
Handling yaml with python
Serial communication with python
UnicodeEncodeError:'cp932' during python scraping
Handling json in python
[Python for Hikari-] Chapter 07-01 Exception Handling (Errors and Exceptions)
Exception message in Python
Evernote API in Python
OpenCV3 Python API list
WiringPi-SPI communication using Python
Python decimal point handling
Hexadecimal handling in Python 3
HTTP communication with Python
C API in Python 3
TensorFlow API memo (Python)
Python exception class list
Fizzbuzz with exception handling
Hit Mastodon's API in Python
Use Trello API with python
AWS CDK-Lambda + API Gateway (Python)
EXE Web API by Python
Use Twitter API with Python
[Python] Passing values during multiprocessing
Exception handling using Python's ZeroDivisionError
Introduction to serial communication [Python]
python> Handling of 2D arrays
Handling of python on mac
Web API with Python + Falcon
View Python communication with Fiddler
Play RocketChat with API / Python
Blender Python API in Houdini (Python 3)
Call the API with python3.
Use subsonic API with python3
Google Drive Api Tips (Python)
Relative url handling in python
Use e-Stat API from Python
[Python of Hikari-] Chapter 07-02 Exception handling (continuous execution of the program by exception handling)