我有一些困难,结合两个要求,是传达给我的。
我最初的要求是处理我创建的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(请注意,代码中还有其他异常正在处理,但我试图简化上面的逻辑,以使分析更容易)
然后,我收到了第二个要求:除了引发异常之外,我还必须返回一个HTTP错误代码。我在另一个StackOverflow 问题中发现,返回错误代码和一些消息很容易。但是,我没有找到任何能清楚解释如何返回错误代码并同时引发异常的东西。据我所知,提高和回报是相互排斥的陈述。那么,是否有任何解决方案来优雅地将异常处理和HTTP错误结合起来?
例如,下面的片段是可以接受的,还是有更好的方法?我真的很困惑,因为异常应该使用加薪,而HTTP代码需要返回。
else:
return SomeRandomException(
f"Encountered errors while inserting rows into table: {errors}"
), 500发布于 2022-02-27 21:44:17
基于约翰的评论。您希望在代码中引发异常,然后添加一次尝试--除非捕获/处理异常并返回错误。
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为了更进一步,您还可以将云测井与Python记录器集成,以便在返回错误之前,还可以将错误记录到云函数的日志中,如:logging.error(err)
这只会有助于使日志以后更容易查询。
https://stackoverflow.com/questions/71287768
复制相似问题