Azure Functions部署Wrike API代码报错:JSON解析失败及日志目录未找到
Azure Function部署后解析Wrike Webhook payload报错问题
我开发了一个Azure Function,通过Wrike API监听TaskParentsAdded、TaskParentsRemoved、TaskCustomFieldChanged事件,用来修改任务前缀。本地运行完全正常,但部署到Azure后,日志流中出现如下错误:
Error: error "syntaxError: Unexpected token "',"'/home/Log"...is not valid JSON" occurred while parsing the response body - '/home/LogFiles/' not found..
疑似存在问题的函数代码:
@app.route(route=MAIN_ROUTE, auth_level=func.AuthLevel.ANONYMOUS) def main(req, context):#Retrieve the payload from the request try: #this should apply in production payload = req.get_json() except: try: #this should apply during testing payload = req.params except: payload = {} logging.info(f'Got request: {payload}')
我曾尝试修改日志配置和端点URL,但导致本地模拟器无法正常运行。
问题根源与修复方案
1. 代码异常处理漏洞
原代码的裸except会捕获所有异常,包括日志系统的错误,且未处理Wrike Webhook可能的非JSON请求格式。同时直接打印payload时,若内容含特殊字符会触发JSON解析错误。
修改后的代码:
import json from azure.functions import HttpRequest @app.route(route=MAIN_ROUTE, auth_level=func.AuthLevel.ANONYMOUS) def main(req: HttpRequest, context): payload = {} try: # 优先解析JSON格式(Wrike Webhook默认使用JSON) payload = req.get_json() except json.JSONDecodeError: # JSON解析失败时,尝试读取原始请求体或表单数据 try: raw_body = req.get_body().decode('utf-8') logging.info(f"Raw request content: {raw_body}") # 处理表单格式的请求 if req.content_type == 'application/x-www-form-urlencoded': payload = dict(req.form) else: payload = {"raw_content": raw_body} except Exception as e: logging.error(f"Failed to parse request: {str(e)}") except Exception as e: logging.error(f"Unexpected error: {str(e)}") # 用JSON序列化后输出日志,避免格式错误 logging.info(f'Parsed payload: {json.dumps(payload)}') # 后续业务逻辑... return HttpResponse("Processed", status_code=200)
2. LogFiles目录访问错误
Azure Functions中不要直接访问/home/LogFiles/目录,内置的logging模块会自动将日志输出到Azure Portal的日志流或Application Insights中。保持默认的host.json日志配置即可:
{ "version": "2.0", "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true, "excludedTypes": "Request" } } } }
3. 恢复本地模拟器运行
- 还原之前修改的端点URL,保持与
local.settings.json中的配置一致 - 确保本地Azure Functions Core Tools版本与Azure上的函数运行时版本匹配(可在Azure Portal的函数应用配置中查看运行时版本)
内容的提问来源于stack exchange,提问作者Anusha Jan Qaisar
相关产品推荐
相关产品推荐

