python - 如何在 Python Azure 函数中捕获 Azure 表引发的异常
问题描述
问题
我有一个用 Python 3.8 编写的 Azure Function HTTP 触发函数。此函数接收传入的 HTTP 请求并将实体写入 Azure 表。如果传入请求尝试创建重复条目,Azure Table 会EntityAlreadyExists
向 Azure Function 运行器抛出错误。我想捕捉这个异常并相应地处理它。
我可以使用 Azure 函数中的 try
/except
块在 python 中捕获此异常吗?如果是这样,怎么做?如果不是,你知道为什么吗?
我尝试过的事情
try
运行代码,然后except ValueError as err:
处理异常try
运行代码,然后except Exception as err:
处理异常try
运行代码,然后except EntityAlreadyExists as err:
处理异常
这些都没有成功捕获从 Azure Table 引发的重复输入尝试的异常。
链接
- c# 的相关问题:How to catch an Exception throw by Azure Table in an async Azure Function HTTP Triggered function。
- 表服务错误代码:https ://docs.microsoft.com/en-us/rest/api/storageservices/table-service-error-codes
抛出错误
这是我试图从 HTTP 触发的 Azure 函数中捕获的错误
Executed 'Functions.myTable' (Failed, Id=xxx-xxx-xxx-xxx, Duration=1256ms)
System.Private.CoreLib: Exception while executing function: Functions.myTable. Microsoft.Azure.WebJobs.Host: Error while handling parameter _binder after function returned:. Microsoft.Azure.WebJobs.Extensions.Storage: The specified entity already exists.
RequestId:xxx-xxx-xxx-xxx
Time:2020-09-30T13:16:00.9339049Z (HTTP status code 409: EntityAlreadyExists. The specified entity already exists.
RequestId:xxx-xxx-xxx-xxx
Time:2020-09-30T13:16:00.9339049Z). Microsoft.WindowsAzure.Storage: The specified entity already exists.
RequestId:xxx-xxx-xxx-xxx
Time:2020-09-30T13:16:00.9339049Z.
--init--.py
下面是 Azure 函数的 py 文件的相关部分。问题围绕第 16-27 行中的try
/except
块(未显示行号)。
import logging
import json
import azure.functions as func
def main(req: func.HttpRequest, myTable: func.Out[str]) -> func.HttpResponse:
body = req.get_json()
data = { # Data to send to Azure Table
"PartitionKey": body.get('var1'),
"RowKey": body.get('var2'),
"Property1" : body.get('var3'),
"Property2" : body.get('var4')
}
try: # Try to send record to Azure Table
myTable.set(json.dumps(data))
except ValueError as err: # Respond with 409 if duplicate record
logging.error(err)
return func.HttpResponse(
body=f'Record already exists.',
status_code=409
)
else: # Otherwise, respond with 201 success
return func.HttpResponse(
body=f'Success.',
status_code=201
)
函数.json
下面是 Azure 函数的触发器和绑定 json。
{
"scriptFile": "__init__.py",
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"post"
]
},
{
"name": "myTable",
"type": "table",
"tableName": "myTable",
"connection": "AzureWebJobsStorage",
"direction": "out"
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
解决方案
如果你使用的是 python。Python只能使用声明式绑定方式,而不能使用命令式绑定方式,所以如果要使用绑定来实现,是不可能使用'try catch'的。
正确的做法是将逻辑放在函数的内容中,然后可以使用 try catch。
推荐阅读
- php - 调用未定义函数 gnupg_init()
- resttemplate - 休息模板没有给出正确的响应体
- python - 自定义召回指标给出错误结果且不更新 - tensorflow
- snowflake-cloud-data-platform - 复制命令不处理任何文件
- reactjs - 在启动之前从后端 api 响应加载配置
- embedded-linux - Linux 不会自动加载内核模块
- huggingface-transformers - 如何从拥抱脸应用预训练的变压器模型?
- unit-testing - NUnit 测试返回列表的控制器方法
- regex - 谷歌表替换正则表达式公式
- mysql - 如何使用 express 将用户变量输入到 mysql 查询中?