
本文旨在解决 azure function 中处理 http 请求时可能遇到的“unexpected end of request content”错误。通过详细阐述如何优化请求体解析机制,避免 `req.get_json()` 潜在的隐患,并引入 `req.get_body()` 结合显式 json 解析及 `incompleteread` 异常处理,从而提升函数的健壮性和错误处理能力,确保在接收不完整或格式异常的请求时能够优雅地响应。
在开发 Azure Function 处理 HTTP 请求,特别是接收 Webhook 数据时,开发者可能会遇到日志中出现“Unexpected end of request content”的错误。这个错误通常发生在函数尝试读取或解析 HTTP 请求体时,表明请求内容在预期结束之前就中断了,导致解析失败。这可能是由于客户端发送了不完整的请求、网络中断或服务器端在读取请求流时遇到了问题。
Azure Functions 提供的 func.HttpRequest 对象包含 get_json() 方法,它旨在方便地将请求体解析为 JSON 对象。然而,当请求体不完整或格式不正确时,get_json() 方法可能会在内部抛出异常,并且这些异常可能不会被外部的 try-except 块有效捕获,或者会转化为更通用的“Unexpected end of request content”日志信息,使得问题难以定位和处理。
为了更精细地控制请求体的读取和解析过程,并捕获更多类型的潜在错误,建议避免直接使用 req.get_json(),而是采用分步处理的方式。
解决此问题的核心在于显式地获取原始请求体内容,然后手动进行 JSON 解析,并在此过程中捕获可能出现的特定异常。
以下是改进后的请求体处理逻辑示例:
import os
import base64
import json
import jwt
from hashlib import md5
from datetime import datetime, timedelta
import azure.functions as func
import logging
import requests
from http.client import IncompleteRead # 导入 IncompleteRead 异常
def webhook_decoder_baas(req: func.HttpRequest) -> func.HttpResponse:
try:
# ... (省略私钥、公钥等初始化代码)
private_key = os.environ["private_key_baas"]
private_key_baas = base64.b64decode(private_key).decode("utf-8")
qi_public_key = '''-----BEGIN PUBLIC KEY-----
... :)
-----END PUBLIC KEY-----'''
authorization = req.headers.get("AUTHORIZATION")
if not authorization:
logging.error("AUTHORIZATION header not provided.")
return func.HttpResponse("AUTHORIZATION header not provided.", status_code=400)
# 优化请求体处理部分
try:
body = req.get_body() # 获取原始字节流
if body is None or len(body) == 0:
logging.error("Empty or missing request body.")
return func.HttpResponse("Empty or missing request body.", status_code=400)
body_json = json.loads(body) # 显式解析 JSON
except ValueError as json_error:
# 捕获 JSON 解析错误
logging.error(f"Error parsing JSON: {str(json_error)}")
return func.HttpResponse("Error parsing JSON", status_code=400)
except IncompleteRead as incomplete_read_error:
# 捕获请求内容不完整错误
logging.error(f"Incomplete read error: {str(incomplete_read_error)}")
return func.HttpResponse("Incomplete read error", status_code=400)
# JWT 解码和断言验证
decoded_header = jwt.decode(token=authorization, key=qi_public_key)
# 使用断言进行数据验证,并提供清晰的错误信息
assert decoded_header.get("method") == "POST", "Error in the sending method, a different method than POST was used."
assert decoded_header.get("payload_md5") == md5(json.dumps(body_json).encode()).hexdigest(), "Payload hash does not match the expected one."
assert (datetime.utcnow() - timedelta(minutes=5)) < datetime.strptime(decoded_header.get("timestamp"), "%Y-%m-%dT%H:%M:%S.%fZ") < (datetime.utcnow() + timedelta(minutes=5)), "Error in sending timestamp, outside the 10-minute limit."
# ... (原有业务逻辑:数据提取、创建新 JSON、发送 POST 请求等)
payload_string = json.dumps(body_json)
objeto_payload = json.loads(payload_string) # 这一步实际上是多余的,body_json已经是Python对象
if (
objeto_payload.get("webhook_type") == "bank_slip.status_change" and
(objeto_payload.get("status") == "payment_notice" or objeto_payload.get("status") == "notary_office_payment_notice")
):
bank_slip_key = objeto_payload.get("data", {}).get("bank_slip_key")
paid_amount = objeto_payload.get("data", {}).get("paid_amount")
payload_output = {
key: objeto_payload[key] for key in ["status"]
}
payload_output['Paid amount'] = paid_amount
payload_output['Query key of the title'] = bank_slip_key
url = "https://nerowebhooks.azurewebsites.net/api/information/send"
token = jwt.encode(payload_output, private_key_baas, algorithm='ES512')
headers = {'SIGNATURE': token}
response = requests.post(url, headers=headers, json=payload_output)
logging.info(f"Received webhook: {payload_output}")
return func.HttpResponse("Webhook received successfully!", status_code=200)
else:
logging.info("Webhook received successfully, but it won't be handled at the moment!")
return func.HttpResponse("Webhook received successfully, but it won't be handled at the moment!")
# 集中处理 JWT 相关的错误
except jwt.JWTError as jwt_error:
logging.error(f"Token error: {str(jwt_error)}")
return func.HttpResponse(f"Token error: {str(jwt_error)}", status_code=400)
# 集中处理断言错误
except AssertionError as assertion_error:
logging.error(f"Assertion error: {str(assertion_error)}")
return func.HttpResponse(str(assertion_error), status_code=400)
# 捕获所有其他未预料的内部错误
except Exception as e:
logging.error(f"Internal error while processing the webhook: {str(e)}")
return func.HttpResponse(f"Internal error while processing the webhook: {str(e)}", status_code=500)
代码改进点说明:
通过上述优化,您的 Azure Function 将能更健壮地处理各种 HTTP 请求,特别是那些可能存在内容不完整或格式异常的 Webhook,显著提高服务的稳定性和可靠性。
以上就是Azure Function Webhook 请求内容异常处理与健壮性优化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号