我在結合傳達給我的兩個要求時遇到了一些麻煩。
我最初的要求是在我創建的 GCP 云函式中處理例外,以便將 JSON 資料插入 BigQuery。基本邏輯如下:
import json
import google.auth
from google.cloud import bigquery
class SomeRandomException(Exception):
"""Text explaining the purpose of this exception"""
def main(request):
"""Triggered by another HTTP request"""
# Instantiation of BQ client
credentials, your_project_id = google.auth.default(
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
client = bigquery.Client(credentials=credentials, project=your_project_id, )
# JSON reading
json_data: dict = request.get_json()
final_message: str = ""
table_name = "someTableName"
for row in json_data:
rows_to_insert: list = []
rows_to_insert.append(row["data"])
if rows_to_insert:
errors: list = client.insert_rows_json(
table_name, rows_to_insert, row_ids=[None] * len(rows_to_insert)
)
if errors == []:
final_message = f"\n{len(rows_to_insert)} row(s) successfully inserted in table\n"
else:
raise SomeRandomException(
f"Encountered errors while inserting rows into table: {errors}"
)
return final_message
(請注意,代碼中還處理了其他例外,但我試圖簡化上述邏輯以使事情更易于分析)
Then I received a second requirement saying that, in addition to raising an exception, I had to return a HTTP error code. I discovered in another StackOverflow question that it was easy to return an error code along with some message. But I haven't found anything that clearly explains how to return that error code and, at the same time, raise an exception. From what I know, raise and return are mutually exclusive statements. So, is there any solution to gracefully combine the exception handling and the HTTP error?
Would the below snippet for instance be acceptable or is there a better way? I'm really confused because an exception is supposed to use a raise whereas a HTTP code needs a return.
else:
return SomeRandomException(
f"Encountered errors while inserting rows into table: {errors}"
), 500
uj5u.com熱心網友回復:
以約翰的評論為基礎。您想在您擁有的代碼中引發例外,然后添加一個 try-except 來捕獲/處理例外并回傳錯誤。
class SomeRandomException(Exception):
# add custom attributes if need be
pass
try:
# your code ...
else:
raise SomeRandomException("Custom Error Message!")
except SomeRandomException as err:
# caught exception, time to return error
response = {
"error": err.__class__.__name__,
"message": "Random Exception occured!"
}
# if exception has custom error message
if len(err.args) > 0:
response["message"] = err.args[0]
return response, 500
更進一步,您還可以將Cloud Logging與 Python 根記錄器集成,這樣在回傳錯誤之前,您還可以將錯誤記錄到 Cloud Function 的日志中,如下所示:
logging.error(err)
這只會幫助以后更容易查詢日志。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/435524.html
標籤:python-3.x http 例外 谷歌云平台 谷歌云功能
上一篇:是否保證未捕獲的例外訊息
下一篇:如何修復目錄匯入'@angular-devkit\build-angular\src\dev-server'不支持在將Angular更新到版本13后決議ES模塊
